请查看以下代码段:
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'变量中。 由于“行”的类型为字符串,因此其内容存储在字符串池中。 Java垃圾收集器不会收集存储在字符串池中的字符串,并且在程序的整个生命周期中都将其保留在那里。
如果文件很大,则字符串池可能会膨胀。您是否知道如何在没有将所有行存储在字符串池中的情况下读取文件?我只是将文件行存储为任何对象,这意味着它在不需要时将从堆中删除。