Reputation: 1260
I'm trying some Java.io classes such as File, FileWriter, BufferedWriter and PrintWriter.
I didn't understand why FileWrite .write()
methods are always printed before all the others bufferedWriter and printWriter's .write()
and/or .println()
methods.
try(FileWriter fileWriter = new FileWriter("file.res");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
PrintWriter printWriter = new PrintWriter(bufferedWriter)){
bufferedWriter.write("BufferedReader\n");
printWriter.println("PrintWriter");
fileWriter.write("FileWriter\n");
}catch (Exception e){
e.printStackTrace();
}
produces as output:
FileWriter
BufferedReader
PrintWriter
Is it normal? Why?
Upvotes: 0
Views: 135
Reputation: 11122
Yes it is.
FileWriter
is not buffered, so writing to it writes immeditately to disk.
BufferedWriter
writes first to a buffer (in memory). The PrintWriter
itself is not buffered, so it writes immediately to the underlying BufferedWriter
and therefore writes to memory too. For these two, the order of write operations is kept, because they are written in the same order to memory.
When the try-with-resources
block is finished, the resources (Writers) are implicitly closed. Before being closed, the flush method of the writer is invoked, causing the contents of the buffer to be written to the underlying writer - the FileWriter
- and therefore to disk.
So the order of execution is
bufferedWriter.write("BufferedReader\n"); -> buf[0..n]
printWriter.println("PrintWriter"); -> buf[n+1...m]
fileWriter.write("FileWriter\n"); -> file[0..a]
//implicit close
bufferdWriter.close(); buf[0..m] -> file[a+1..a+m]
And the file result will look like
file[0..a,a+1..a+n,a+n+1..a+m]
^ ^ ^ ^ ^ ^
|FW| | BW | | PW |
Upvotes: 2