如何使用Java逐行读取大型文本文件?我需要使用Java逐行读取5-6GB左右的大型文本文件。我怎么能这么快做呢?
4 回答
回首忆惘然
TA贡献1847条经验 获得超11个赞
try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { // process the line. }}
line
try(BufferedReader br = new BufferedReader(new FileReader(file))) { for(String line; (line = br.readLine()) != null; ) { // process the line. } // line is not visible here.}
try (Stream<String> stream = Files.lines(Paths.get(fileName))) { stream.forEach(System.out::println);}
富国沪深
TA贡献1790条经验 获得超9个赞
可以指定缓冲区大小,也可以使用默认大小。对于大多数用途,缺省值都足够大。
// Open the fileFileInputStream fstream = new FileInputStream("textfile.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream));String strLine; //Read File Line By Linewhile ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println (strLine);}//Close the input streamfstream.close();
汪汪一只猫
TA贡献1898条经验 获得超8个赞
try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) { lines.forEachOrdered(line -> process(line));}
try (Stream<String> lines = Files.lines(file, Charset.defaultCharset())) { lines.forEachOrdered(System.out::println);}
有只小跳蛙
TA贡献1824条经验 获得超8个赞
InputStream ins = null; // raw byte-streamReader r = null; // cooked readerBufferedReader br = null; // buffered for readLine()try { String s; ins = new FileInputStream("textfile.txt"); r = new InputStreamReader(ins, "UTF-8"); // leave charset out for default br = new BufferedReader(r); while ((s = br.readLine()) != null) { System.out.println(s); }}catch (Exception e){ System.err.println(e.getMessage()); // handle exception}finally { if (br != null) { try { br.close(); } catch(Throwable t) { /* ensure close happens */ } } if (r != null) { try { r.close(); } catch(Throwable t) { /* ensure close happens */ } } if (ins != null) { try { ins.close(); } catch(Throwable t) { /* ensure close happens */ } }}
File f = new File("textfile.txt");f.withReader("UTF-8") { br -> br.eachLine { line -> println line; }}
添加回答
举报
0/150
提交
取消