请看下面的代码片段:
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"myfile.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
如您所见,文件的每一行都被读取并存储在“line”变量中。由于 'line' 是字符串类型,它的内容存储在字符串池中。存储在字符串池中的字符串不会被 Java 垃圾收集器收集,而是在程序的整个生命周期内都保留在那里。
如果文件非常大,字符串池可能会膨胀。您知道如何在不将所有行都存储在字符串池中的情况下读取文件吗?我只是将文件行存储为任何对象,这意味着它会在不需要时从堆中删除。