Java FileOutputStream
What FileOutputStream Is
java.io.FileOutputStream writes raw bytes to a file. It's a subclass of OutputStream, the base class for every byte destination in Java, and the counterpart of FileInputStream.
Use it when the data isn't text or when you control the exact bytes yourself: saving downloaded files and uploads, copying files, writing images, audio, archives or any binary format. For text, use a writer (BufferedWriter, Files.writeString), which converts characters to bytes with a charset for you.
Writing Bytes
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Arrays;
public class O1 {
public static void main(String[] args) throws IOException {
try (FileOutputStream out = new FileOutputStream("bytes.bin")) {
out.write(65);
out.write(300);
out.write(new byte[] {10, 20, 30});
byte[] data = {1, 2, 3, 4, 5, 6};
out.write(data, 2, 3);
out.write("₹".getBytes(StandardCharsets.UTF_8));
}
System.out.println(Arrays.toString(Files.readAllBytes(Path.of("bytes.bin"))));
try (FileOutputStream out = new FileOutputStream("bytes.bin")) {
out.write(99);
}
System.out.println("after reopening: " + Arrays.toString(Files.readAllBytes(Path.of("bytes.bin"))));
try (FileOutputStream out = new FileOutputStream("bytes.bin", true)) {
out.write(100);
}
System.out.println("after append: " + Arrays.toString(Files.readAllBytes(Path.of("bytes.bin"))));
try {
new FileOutputStream("no/such/folder/x.bin").close();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException: " + e.getMessage());
}
}
}
Output (on Linux):
[65, 44, 10, 20, 30, 3, 4, 5, -30, -126, -71]
after reopening: [99]
after append: [99, 100]
FileNotFoundException: no/such/folder/x.bin (No such file or directory)
The write methods
| Method | Writes |
|---|---|
write(int b) | One byte: the lowest 8 bits of b |
write(byte[] b) | The whole array |
write(byte[] b, int off, int len) | len bytes starting at index off |
Walking through the first file:
write(65)writes one byte with the value 65.write(300)writes 44, not 300. A byte can only hold 8 bits, so the higher bits are discarded: 300 is1_0010_1100in binary, and its lowest 8 bits0010_1100are 44. No exception is thrown, so passing a value outside 0–255 silently writes something else. This is a common bug when writing numbers to binary files — numbers larger than a byte must be split into several bytes explicitly, as the BMP example below does.write(new byte[] {10, 20, 30})writes three bytes.write(data, 2, 3)writes 3 bytes starting at index 2:3, 4, 5.- Text must be converted to bytes with a charset first.
"₹".getBytes(UTF_8)gives three bytes, whichArrays.toStringprints as signed values (-30, -126, -71areE2 82 B9).
Overwrite or append
new FileOutputStream(name)creates the file if needed, and truncates it if it already exists. Reopening the file and writing99replaced all eleven earlier bytes.new FileOutputStream(name, true)opens the file in append mode: new bytes go at the end.
The constructors also accept a File (new FileOutputStream(file, true)).
Errors
The constructor throws FileNotFoundException when the file can't be opened for writing — here because the folder doesn't exist (FileOutputStream never creates parent folders), but also when the path is a folder or permission is denied. Create folders first with Files.createDirectories.
Copying a File with a Buffer
The most common use of FileOutputStream is the read-buffer-write loop: read a block from an input stream, write the same block to the output stream, repeat until the end.
import java.io.*;
import java.nio.file.*;
import java.util.Random;
public class Copy {
static long copy(Path source, Path target, long reportEvery) throws IOException {
long total = 0, nextReport = reportEvery;
long size = Files.size(source);
try (InputStream in = new FileInputStream(source.toFile());
OutputStream out = new FileOutputStream(target.toFile())) {
byte[] buffer = new byte[64 * 1024];
int n;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
total += n;
if (total >= nextReport || total == size) {
System.out.printf(" %3d%% (%,d of %,d bytes)%n", total * 100 / size, total, size);
nextReport += reportEvery;
}
}
}
return total;
}
public static void main(String[] args) throws IOException {
byte[] video = new byte[1_000_000];
new Random(42).nextBytes(video);
Path src = Files.write(Path.of("lecture.mp4"), video);
long copied = copy(src, Path.of("lecture-backup.mp4"), 300_000);
System.out.println("copied " + copied + " bytes, identical: "
+ (Files.mismatch(src, Path.of("lecture-backup.mp4")) == -1));
}
}
Output:
32% (327,680 of 1,000,000 bytes)
65% (655,360 of 1,000,000 bytes)
91% (917,504 of 1,000,000 bytes)
100% (1,000,000 of 1,000,000 bytes)
copied 1000000 bytes, identical: true
How it works:
- Test data.
Random(42).nextBytesfills a megabyte with pseudo-random bytes, standing in for a video file. A fixed seed makes the run repeatable. - Both streams in one try-with-resources. They're closed in reverse order — the output stream first, which completes the file, then the input stream — even if copying fails.
out.write(buffer, 0, n)writes exactly thenbytes that were read. Writing the wholebufferinstead would append stale bytes from the previous block at the end of the copy, producing a corrupted file that's slightly too large.- Progress reporting. The copy runs in 64 KB blocks (65,536 bytes), so progress is printed at the first block boundary past each 300,000-byte step, and once more at 100%. Showing progress like this is the reason to write the loop yourself.
- Verification.
Files.mismatchreturns-1when two files are byte-for-byte identical.
When you don't need progress or any processing of the bytes, the JDK does the same work in one call:
in.transferTo(out); // stream to stream (Java 9+)
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); // file to file
Files.copy(inputStream, target); // e.g. an HTTP download or an upload to a file
Files.copy between two files can also use operating-system shortcuts that avoid copying data through Java at all.
Flushing and Syncing
FileOutputStream has no buffer of its own: each write call goes directly to the operating system. Its flush() method therefore does nothing. That has two consequences:
- Many small writes (single bytes, small arrays) are slow, because each one is a system call. Wrap the stream in a
BufferedOutputStreamwhen writing in small pieces, as the BMP example does. ABufferedOutputStreamdoes need flushing or closing, or its last bytes won't reach the file. - Once
writereturns, the data has been handed to the operating system, which normally writes it to disk shortly afterwards. If the data must be on the physical disk before your program continues — for example before reporting "payment recorded" — callout.getFD().sync(). This forces the operating system to write its cached data to the device. It's much slower, so use it only where durability really matters.
FileOutputStream and Files.newOutputStream
try (OutputStream out = Files.newOutputStream(Path.of("export.zip"))) { ... }
try (OutputStream out = Files.newOutputStream(Path.of("audit.bin"),
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { ... }
Files.newOutputStream returns an equivalent OutputStream for a Path, accepts open options such as CREATE_NEW (fail instead of overwriting) and throws NIO's more specific exceptions. Both are fine; Files.newOutputStream fits naturally into code that already uses Path.
Practical Example: Writing a Binary Image Format
Binary file formats define exactly which bytes go where. This example writes a valid BMP image — one of the simplest image formats — byte by byte, then reads it back with the JDK's image library to prove the file is correct. The same techniques apply to any binary format: fixed headers, multi-byte numbers in a specific byte order, and padding.
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.*;
import javax.imageio.ImageIO;
public class Bmp {
static void writeIntLE(OutputStream out, int v) throws IOException {
out.write(v);
out.write(v >>> 8);
out.write(v >>> 16);
out.write(v >>> 24);
}
static void writeShortLE(OutputStream out, int v) throws IOException {
out.write(v);
out.write(v >>> 8);
}
// pixels[row][col] = 0xRRGGBB, row 0 is the top row
static void writeBmp(Path file, int[][] pixels) throws IOException {
int height = pixels.length, width = pixels[0].length;
int rowSize = (width * 3 + 3) / 4 * 4; // each row is padded to a multiple of 4 bytes
int imageSize = rowSize * height;
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {
out.write('B'); out.write('M'); // file header (14 bytes)
writeIntLE(out, 14 + 40 + imageSize); // total file size
writeIntLE(out, 0); // reserved
writeIntLE(out, 14 + 40); // offset of pixel data
writeIntLE(out, 40); // info header size (40 bytes)
writeIntLE(out, width);
writeIntLE(out, height);
writeShortLE(out, 1); // colour planes
writeShortLE(out, 24); // bits per pixel
writeIntLE(out, 0); // no compression
writeIntLE(out, imageSize);
writeIntLE(out, 2835); // 72 DPI horizontally
writeIntLE(out, 2835); // 72 DPI vertically
writeIntLE(out, 0); // palette colours
writeIntLE(out, 0); // important colours
for (int row = height - 1; row >= 0; row--) { // BMP stores the bottom row first
for (int col = 0; col < width; col++) {
int rgb = pixels[row][col];
out.write(rgb); // blue
out.write(rgb >>> 8); // green
out.write(rgb >>> 16); // red
}
for (int p = width * 3; p < rowSize; p++) out.write(0);
}
}
}
public static void main(String[] args) throws IOException {
int[][] flag = {
{0xFF9933, 0xFF9933, 0xFF9933},
{0xFFFFFF, 0x000080, 0xFFFFFF},
{0x138808, 0x138808, 0x138808}};
Path file = Path.of("flag.bmp");
writeBmp(file, flag);
System.out.println("file size: " + Files.size(file) + " bytes");
BufferedImage img = ImageIO.read(file.toFile());
System.out.printf("read back: %dx%d, top-left #%06X, centre #%06X, bottom-right #%06X%n",
img.getWidth(), img.getHeight(),
img.getRGB(0, 0) & 0xFFFFFF, img.getRGB(1, 1) & 0xFFFFFF, img.getRGB(2, 2) & 0xFFFFFF);
}
}
Output:
file size: 90 bytes
read back: 3x3, top-left #FF9933, centre #000080, bottom-right #138808
The resulting flag.bmp opens in any image viewer as a tiny 3×3 tricolour. How the code produces valid bytes:
- Splitting integers into bytes. A BMP header stores numbers as 4-byte (and 2-byte) values in little-endian order — least significant byte first.
writeIntLEwritesv, thenv >>> 8,v >>> 16andv >>> 24. Eachwrite(int)keeps only the lowest 8 bits, so each call outputs exactly one byte of the number. Here, the "only the lowest 8 bits" behaviour that silently produced 44 earlier is used on purpose. - The headers. The file starts with the signature
BM(the magic number checked by readers), then the total size, the position of the pixel data, and a 40-byte information header with width, height, 24 bits per pixel and no compression. The comments mark each field in the order the format specifies. - Pixel order. Each pixel is written as blue, green, red — BMP's order, the reverse of the usual RGB notation. Rows are written bottom to top, so the loop starts at the last row.
- Row padding. Each row must occupy a multiple of 4 bytes. A row of 3 pixels is 9 bytes, so 3 zero bytes of padding are added, making 12.
(width * 3 + 3) / 4 * 4rounds up to the next multiple of 4 using integer division. - Size check. 14 (file header) + 40 (info header) + 3 rows × 12 bytes = 90 bytes, matching the output.
- Buffering. The image is written in single bytes, so a
BufferedOutputStreamcollects them and passes them to theFileOutputStreamin large blocks. Closing it (by try-with-resources) flushes the last bytes; without that, the file would be incomplete. - Verification.
ImageIO.readparses the file with the JDK's own BMP decoder and returns the correct dimensions and colours, which confirms every byte is in the right place.getRGBreturns the alpha channel in the top byte too, so& 0xFFFFFFkeeps only the colour.
For formats with many numeric fields, the JDK can do the byte splitting for you. DataOutputStream (Data Streams lesson) writes numbers in big-endian order, which suits network protocols and Java's own formats but not BMP. ByteBuffer lets you choose: ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v).array() produces the same four bytes as writeIntLE.