I am quite confused here. I am preparing to SCJP, I wrote a small recursive to check BufferedWriter memory allocations before|after flush() & close() methods. Please see below code block, I have just wrote my Desktop files into a text file.
import java.io.*;
public class Myexception{
private static String lvl = "";
static BufferedWriter bw;
private static File source = new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\New folder\\myTest.txt");
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
System.out.println("Free memory before recursive: " + rt.freeMemory());
bw = new BufferedWriter(new FileWriter(source));
checkFiles(new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop"), 0);
System.out.println("Memory after recursive: " + rt.freeMemory());
bw.flush();
bw.close();
lvl = null;
System.out.println("Memory after clean up: " + rt.freeMemory());
}
static void checkFiles(File file, int level) throws IOException{
if(!file.exists()){
System.out.println("File doesnt exist: " + file.getName() + file.getPath());
return;
}
for(String s:file.list()){
if(new File(file.getPath() + "\\" + s).isDirectory()){
bw.newLine();
bw.write(lvl + "Directory: " + s);
lvl += " ";
checkFiles(new File(file.getPath() + "\\" + s), level+1);
}else{
bw.newLine();
bw.write(lvl + "File: " + s);
}
}
}
}
Output is fine but what I didnt understand, free memory before than flush() & close() is the same as after than flush() & close().Please see my output:
Free memory before recursive: 126150232
Memory after recursive: 104461304
Memory after clean up: 104461304
I have checked existing topics but I couldn`t find exact explanation. I was expecting I will have more free memory after bw.close().
Thank you