我需要使用Java逐行读取大约5-6 GB的大型文本文件。
我怎样才能快速做到呢?
我需要使用Java逐行读取大约5-6 GB的大型文本文件。
我怎样才能快速做到呢?
当前回答
我的阅读习惯通常很简单:
void readResource(InputStream source) throws IOException {
BufferedReader stream = null;
try {
stream = new BufferedReader(new InputStreamReader(source));
while (true) {
String line = stream.readLine();
if(line == null) {
break;
}
//process line
System.out.println(line)
}
} finally {
closeQuiet(stream);
}
}
static void closeQuiet(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignore) {
}
}
}
其他回答
Java 9:
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
}
FileReader不会让你指定编码,如果你需要指定它,使用inputstreamreader代替:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
如果从Windows导入该文件,它可能具有ANSI编码(Cp1252),因此必须指定编码。
看看这个博客:
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读取文件
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();
}
}
}
一种常见的模式是使用
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
如果假设没有字符编码,则可以更快地读取数据。例如,ASCII-7,但它不会有太大的区别。很有可能您对数据的处理将花费更长的时间。
EDIT:一种不太常用的模式,可以避免行泄漏的范围。
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
// process the line.
}
// line is not visible here.
}
更新:在Java 8中你可以这样做
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
}
注意:你必须将Stream放在try-with-resource块中,以确保对其调用#close方法,否则底层文件句柄永远不会关闭,直到GC在很久之后才关闭。