一般读取文件文本的写法:
- 使用BufferedReader来逐行读取文本内容
File file =new File("test.txt");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
如果文本文件体积够大的话,运行一段时间会抛出内存溢出的异常.
原因分析:文件的所有行都被存放在内存中,当文件足够大时很快就会导致程序抛出OutOfMemoryError 异常。
我就是因为经验不足,使用了这种写法,导致运行一段时间就抛出异常
- 正确的做法:
File file =new File("test.txt");
try (
FileInputStream fis = new FileInputStream(file);
Scanner sc = new Scanner(fis, "UTF-8")
) {
while (sc.hasNext()) {
String line = sc.nextLine();
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
该方案将会遍历文件中的所有行,允许对每一行进行处理,而不保持对它的引用。总之没有把它们存放在内存中
以上分析和解决思路来自:https://www.jb51.net/article/120760.htm