Please take a look at the following code snippet:
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();
}
}
As you can see, every line of the file is read and stored in 'line' variable. Since 'line' is of type string, its content is stored in string pool. Strings stored in string pool are not collected by Java garbage collector and stay there for the entire lifetime of the program.
In case the file is very big, string pool can be bloated. Do you have any idea how to read the file without storing all of its lines in the string pool? I just was to store the file lines as any object, meaning that it will removed from heap when it's not needed.