FileOutputStream
In short: A byte stream for raw, unbuffered writing into a file — the counterpart to FileInputStream for the write direction.
In more detail: As with reading, a raw, unbuffered byte stream is also inefficient for writing when there are many small write operations — it’s therefore common to combine it with a buffered wrapper, which collects data and writes it in larger blocks. It’s important to close the stream after writing, so buffered data actually reaches the storage device.
In Depth
try (FileOutputStream fos = new FileOutputStream("output.bin")) {
fos.write(byteArray);
}Just like FileInputStream, this stream operates at the lowest level with individual bytes, with no interpretation of the content whatsoever — it’s therefore suitable for any binary data (images, compressed files, serialised objects), not just text.
An important additional aspect for writing that doesn’t matter for reading: the mode. A FileOutputStream can by default completely overwrite an existing file, or — via an additional constructor parameter (append = true) — append to the existing content instead of replacing it. If this parameter is forgotten when appending was actually intended (e.g. for a growing log file), all previous content is lost the next time the program starts.
Just as with reading: for pure text, a raw byte stream is rarely the right choice, because the conversion of characters into bytes (the encoding) has to be explicitly accounted for — a character-based writer automatically handles this correctly. A FileOutputStream is typically used directly when already-finished bytes exist (e.g. the content of a downloaded file) that should be written 1:1 unchanged to the storage device.
As with any resource that occupies system handles and can contain buffered data, reliable closing is crucial — on a crash between write() and closing the stream, unbuffered data not yet physically written can be lost. try-with-resources guarantees the closing automatically, even for an exception in the middle of writing.
See also: I/O Streams, BufferedWriter, FileInputStream