The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › I/O
I/O streams and buffers
I called write, so why is the file empty?
Why it exists — If you write one byte at a time directly to a file or a socket, each write costs a call to the operating system, so the more small writes there are, the slower it gets. BufferedOutputStream collects small write requests and passes them to the underlying stream in larger chunks, which reduces the number of calls to the operating system. The price is that the data does not reach the file until the buffer fills or you call flush or close.
Where it's used today — When you read and write files, you use buffered streams such as BufferedReader, BufferedWriter, and Files.newBufferedWriter by default, and you use try-with-resources to make sure they are closed. Text that includes Korean is read with a character stream that has the encoding set to UTF-8. For output that must reach the other side right away, such as a message sent over a socket, you call flush after writing the whole message.
When you write to a file, calling out.write does not mean that the data goes into the file right away. A buffered stream collects data in memory and writes it out all at once. This lab writes the 9 bytes of the three Korean characters "가나다" one byte at a time, counts how many writes actually reach the underlying stream, and then reads the file back both byte by byte and character by character.
Checked against real execution · The 48 combinations were run on JDK 21 and checked against the results
Concepts in this lab
- Byte streams and character streams
- Where it's used today — Use InputStream and OutputStream to save an uploaded image or to copy a file as it is. To read a text file such as a CSV or a log line by line, use a BufferedReader created with Files.newBufferedReader with the encoding specified.
- A stream is a channel through which data flows in sequence from one side to the other, and Java has two kinds: one that handles data in units of bytes and one that handles it in units of characters. The InputStream and OutputStream family are the byte streams, which are used to move content as it is, such as images and compressed files. The Reader and Writer family are the character streams, which convert bytes to characters according to a given encoding. Text in which one character takes several bytes, such as Korean, is garbled if you read it with a byte stream and convert each byte to a character, so use a character stream with a specified encoding to read and write text.
- Buffer and flush
- Where it's used today — Use a buffer when writing a lot of logs to a file or sending a response through a socket. For data that the other side must receive right away, such as a chat message, call flush after writing, and if you close with try-with-resources, close also does the flush.
- A buffer is an area of memory that holds data for a while without sending it out right away. BufferedOutputStream and BufferedWriter collect the data they receive through write in a buffer and, when the buffer becomes full, write it to the underlying stream all at once, which reduces the number of writes to a file or the network. flush is a request to write out what has been collected so far even though the buffer is not full, and close performs a flush before it closes the stream. So if neither flush nor close is called, the data that was left in the buffer is not written to the destination.
- Character encoding and UTF-8
- Why it exists — If every country uses a different encoding (Korea uses EUC-KR and others), characters are garbled when you open a file written in another encoding, and it is hard to mix characters of several countries in one text. UTF-8 writes every Unicode character by one rule, and keeps English letters as 1 byte, the same as ASCII.
- Where it's used today — It is commonly used as the encoding of web pages, JSON, and Java source files. To store even emoji in MySQL, specify the character set as utf8mb4, not utf8.
- A character encoding is a rule that defines which bytes each character is converted to when it is stored. UTF-8 is the most widely used encoding, and the length of a character varies from 1 byte to 4 bytes depending on the character. English letters and digits take 1 byte, and one Korean character takes 3 bytes. Text is garbled when the encoding used for writing differs from the one used for reading, or when the bytes are cut off in the middle of a character, so it is safer to state the encoding explicitly in code that reads and writes text.
- finally and try-with-resources
- A finally block runs whether the try block ends normally or throws an exception (except when the JVM exits during the try, for example through System.exit()), and it is used to clean up resources. The try-with-resources statement lets you declare a resource that implements AutoCloseable inside the parentheses of try, and close() is then called automatically when the block ends. Compared with closing the resource yourself in finally, it leads to fewer forgotten closes and fewer exception-handling mistakes.
Try these
- Default settings — Written through a buffer and not closed. write was called 9 times, but the file has 0 bytes.
- Closing with close — The 9 bytes collected in the buffer are written out in one write and end up in the file.
- Writing with no buffer — The 9 calls to write reach the underlying stream as 9 writes.
- With a 4-byte buffer — The buffer is written out each time it fills up, and if the stream is not closed, the last 1 byte is left behind.
- An exception before close — close never runs, so the file is empty.
- With try-with-resources — Even when an exception is thrown, the stream is closed automatically and the data is written to the file.
- Reading one byte as one character — The three Korean characters become nine garbled characters.
Running with the default settings
- new FileOutputStream("out.txt"): This opens the file for writing. A CountingOutputStream (a class made for this example), which counts write calls, holds a reference to this file stream and passes each write on to it. A BufferedOutputStream whose buffer is 8192 bytes holds a reference to the CountingOutputStream, so out.write goes through the buffer before it reaches the underlying stream.
- The 3 bytes of "가" (EA B0 80), one at a time with out.write(b): All three writes only store the bytes in the buffer, and nothing reaches the underlying stream. The buffer has collected 3 bytes, and the file has 0 bytes.
- The 3 bytes of "나" (EB 82 98), one at a time with out.write(b): All three writes only store the bytes in the buffer, and nothing reaches the underlying stream. The buffer has collected 6 bytes, and the file has 0 bytes.
- The 3 bytes of "다" (EB 8B A4), one at a time with out.write(b): All three writes only store the bytes in the buffer, and nothing reaches the underlying stream. The buffer has collected 9 bytes, and the file has 0 bytes.
- (no closing code): Execution moves on without a call to flush or close. What is left in the buffer (9 bytes) is only in memory and is not in the file. If the program ends like this, that data is lost. The stream is left open and keeps holding the file.
- counting.calls and Files.size: The number of writes that reached the underlying stream is 0, and the file size is 0 bytes. 9 bytes were written, but the file is missing 9 of them.
- Reading the file back: The file is empty, so in.read() returns -1 (the end) from the very first call. No characters are read.
Result of this run
- BufferedOutputStream collects data in a buffer in memory and writes it out all at once. The data is written out only when the buffer becomes full or when flush or close is called. So if the stream is not closed, the data left in the buffer at the end is not written to the file.
Code
// Below the example class are the lines inside main (outer class, main declaration, and imports omitted)
class CountingOutputStream extends OutputStream { // a class made for this example. It counts the write calls that reach it
private final OutputStream out;
int calls = 0;
boolean closed = false;
CountingOutputStream(OutputStream out) { this.out = out; }
@Override public void write(int b) throws IOException { calls++; out.write(b); }
@Override public void write(byte[] b, int off, int len) throws IOException { calls++; out.write(b, off, len); }
@Override public void close() throws IOException { closed = true; out.close(); }
}
byte[] data = "가나다".getBytes(StandardCharsets.UTF_8); // 9 bytes
CountingOutputStream counting = new CountingOutputStream(new FileOutputStream("out.txt"));
OutputStream out = new BufferedOutputStream(counting); // a stream that has a buffer
for (byte b : data) out.write(b); // one byte at a time, 9 times
System.out.println(counting.calls); // number of writes that reached the underlying stream
System.out.println(Files.size(Path.of("out.txt"))); // file size
StringBuilder sb = new StringBuilder(); // read the file back
try (Reader in = new InputStreamReader(new FileInputStream("out.txt"), StandardCharsets.UTF_8)) {
int ch;
while ((ch = in.read()) != -1) sb.append((char) ch); // one character at a time
}
System.out.println(sb);
Assumptions of this model
The results of the 48 combinations (the number of writes that reached the underlying stream and the number of bytes in each one, the file size, whether the stream was closed, and the characters read back) were checked against the results of actually running the code on JDK 21. The following were also confirmed by separate runs on the same JDK: a BufferedOutputStream created without a size writes its data out after it has collected 8192 bytes, the data left in the buffer is not written to the file even when the program ends normally without closing the stream, and the English letters abc stay the same even when each byte is converted to a character. 8192 is the value seen on this JDK and is not a figure that the Java documentation fixes. "File" in the diagram means the point up to which the program has handed the write over to the operating system. The operating system has buffers of its own, so the data may actually be recorded on the disk later than that, and this is not covered. In the result of reading byte by byte, a character that cannot be shown on the screen is displayed as □. The difference in speed with and without a buffer was not measured. Character streams on the writing side (Writer) and write(byte[]), which writes a large chunk at once, are not covered.
Previous lab: Class loading and initialization · Next lab: Serialization