我需要使用Java逐行读取大约5-6 GB的大型文本文件。
我怎样才能快速做到呢?
我需要使用Java逐行读取大约5-6 GB的大型文本文件。
我怎样才能快速做到呢?
当前回答
在Java 8中,除了使用Files.lines(),还有另一种方法。如果您的输入源不是文件,而是更抽象的东西,如Reader或InputStream,则可以通过BufferedReaders lines()方法对行进行流处理。
例如:
try (BufferedReader reader = new BufferedReader(...)) {
reader.lines().forEach(line -> processLine(line));
}
BufferedReader读取的每个输入行都会调用processLine()。
其他回答
使用Java 8读取文件
package com.java.java8;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
/**
* The Class ReadLargeFile.
*
* @author Ankit Sood Apr 20, 2017
*/
public class ReadLargeFile {
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
try {
Stream<String> stream = Files.lines(Paths.get("C:\\Users\\System\\Desktop\\demoData.txt"));
stream.forEach(System.out::println);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
下面是一个完整的错误处理示例,并支持java 7之前的字符集规范。在Java 7中,您可以使用try-with-resources语法,这使得代码更简洁。
如果你只想要默认字符集,你可以跳过InputStream,使用FileReader。
InputStream ins = null; // raw byte-stream
Reader r = null; // cooked reader
BufferedReader br = null; // buffered for readLine()
try {
String s;
if (true) {
String data = "#foobar\t1234\n#xyz\t5678\none\ttwo\n";
ins = new ByteArrayInputStream(data.getBytes());
} else {
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 */ } }
}
下面是Groovy版本,有完整的错误处理:
File f = new File("textfile.txt");
f.withReader("UTF-8") { br ->
br.eachLine { line ->
println line;
}
}
一旦Java 8发布(2014年3月),你就可以使用流了:
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);
}
看看这个博客:
Java逐行读取文件- Java教程
可以指定缓冲区大小或 可以使用默认大小。的 违约对大多数人来说已经足够大了 目的。
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
fstream.close();
在Java 8中,你可以这样做:
try (Stream<String> lines = Files.lines (file, StandardCharsets.UTF_8))
{
for (String line : (Iterable<String>) lines::iterator)
{
;
}
}
一些注释:由Files返回的流。行(不像大多数流)需要关闭。由于这里提到的原因,我避免使用forEach()。奇怪的代码(Iterable<String>) lines::iterator将一个Stream转换为一个Iterable。