Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do PrintWriter automatically print to file?

Tags:

java

After playing with PrintWriter and files, I got a doubt about why do sometimes when I read my files immediately when I create them, there are inconsistencies, for example:

File file = new File("Items.txt");
int loopValue = 10;
try {
    PrintWriter fout = new PrintWriter(file);
    for (int i = 0; i < loopValue; i++) {
        fout.print(i + " asdsadas" + System.lineSeparator());
    }
    //fout.flush(); <-- I know if I call flush or close this problem don't occur
    //fout.close();

    System.out.println("Here is the file:");
    Scanner readFile = new Scanner(file);
    while (readFile.hasNext()) {
        System.out.println(readFile.nextLine());
    }
} catch (FileNotFoundException e) {
    System.err.println(e.getMessage());
}

If I run this code, I will read in console an empty file, something like this:

Here is the file:

But if I modify the loopValue to something like 10000, I will have something like this:

Here is the file:
0 asdsadas
1 asdsadas
2 asdsadas
...
...  continues
...
9356 asdsadas
9357 asdsadas
9358  <--- here ends, note that it doesnt end in the value 9999

I know that if I call flush() or close() before read the file I can rid of this problem, but why is this happening? When do PrintWriter decide that is time to clean its buffer without I tell it when? and why when I close or flush the PrintWriter this problem won't happen?

Thanks!

like image 887
Alex Sifuentes Avatar asked Jul 31 '15 01:07

Alex Sifuentes


1 Answers

The general concept and motivation behind the buffer for PrintWriter is that it is expensive to write something out to the console. Hence, by queueing up pending changes to be output, the program can run more efficiently. Imagine you had a Java program which were doing something very intensive from a CPU point of view, such as heavy calculations in a multithreaded application. Then, if you were also insisting that each call to PrintWriter.print() deliver its output immediately, the program could hang, and overall performance would decline.

If you insist on seeing the output from PrintWriter immediately after the call, then you can call flush() to achieve this. But as already mentioned, there could be a performance penalty under certain conditions.

like image 93
Tim Biegeleisen Avatar answered Oct 13 '22 19:10

Tim Biegeleisen