我有一个包含 2000 万行文本的大型文本文件。当我使用以下程序读取文件时,它工作得很好,实际上我可以读取更大的文件而没有内存问题。
public static void main(String[] args) throws IOException {
File tempFile = new File("temp.dat");
String tempLine = null;
BufferedReader br = null;
int lineCount = 0;
try {
br = new BufferedReader(new FileReader(tempFile));
while ((tempLine = br.readLine()) != null) {
lineCount += 1;
}
} catch (Exception e) {
System.out.println("br error: " +e.getMessage());
} finally {
br.close();
System.out.println(lineCount + " lines read from file");
}
}
但是,如果我需要在读取该文件之前将一些记录附加到该文件中,则 BufferedReader 会消耗大量内存(我刚刚使用 Windows 任务管理器对此进行了监控,我知道这不是很科学,但它证明了问题所在)。修改后的程序如下,与第一个相同,只是我先将一条记录附加到文件中。
public static void main(String[] args) throws IOException {
File tempFile = new File("temp.dat");
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(tempFile, true)));
pw.println(" ");
} catch (Exception e) {
System.out.println("pw error: " + e.getMessage());
} finally {
pw.close();
}
String tempLine = null;
BufferedReader br = null;
int lineCount = 0;
try {
br = new BufferedReader(new FileReader(tempFile));
while ((tempLine = br.readLine()) != null) {
lineCount += 1;
}
} catch (Exception e) {
System.out.println("br error: " +e.getMessage());
} finally {
br.close();
System.out.println(lineCount + " lines read from file");
}
}
Windows 任务管理器的屏幕截图,其中行中的大凸起显示了我运行该程序的第二个版本时的内存消耗。
所以我能够读取这个文件而不会耗尽内存。但是我有超过 5000 万条记录的更大文件,当我对它们运行这个程序时遇到内存不足异常?有人可以解释为什么该程序的第一个版本适用于任何大小的文件,但第二个程序的行为如此不同并以失败告终?我在 Windows 7 上运行:
java 版本 "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) Client VM (build 23.1-b03, 混合模式, 共享)