FileOutputStream Class in Java: Writing Bytes to a File
Saving a downloaded image, exporting a report or writing a log entry all end the same way: bytes are written to a file. FileOutputStream is the basic java.io class for that job.
This tutorial covers its constructors, the difference between overwrite and append mode, its methods and two practical examples.
1. What Is FileOutputStream in Java?
FileOutputStream is a concrete subclass of OutputStream that writes bytes to a file. It has been available since Java 1.0.
- If the file does not exist, it is created; its parent folder must already exist.
- If the file exists, its content is replaced, unless you open it in append mode.
- It is not buffered, so wrap it in a
BufferedOutputStreamwhen writing many small pieces.
2. FileOutputStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of FileOutputStream
| Constructor | Description |
|---|---|
FileOutputStream(String name) | Opens the file at the path, replacing its content. |
FileOutputStream(String name, boolean append) | With true, new bytes are added to the end (Java 1.1). |
FileOutputStream(File file) | Opens the file represented by a File, replacing its content. |
FileOutputStream(File file, boolean append) | Same, with an append option (Java 1.4). |
FileOutputStream(FileDescriptor fdObj) | Writes to an existing file connection. |
The constructors throw FileNotFoundException if the path is a folder or the file cannot be created or opened.
4. Commonly Used Methods
| Method | Description |
|---|---|
void write(int b) | Writes one byte. |
void write(byte[] b) | Writes the whole array. |
void write(byte[] b, int off, int len) | Writes part of an array. |
FileChannel getChannel() | Returns the NIO channel for this file (Java 1.4). |
void close() | Closes the file. Always close it so the operating system releases it. |
5. Example: Overwrite Mode vs Append Mode
A reception desk records visitors in a log file. The first two writes use overwrite mode, the next two use append mode.
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class VisitorLog {
static void save(Path file, String line, boolean append) throws IOException {
try (FileOutputStream out = new FileOutputStream(file.toFile(), append)) {
out.write((line + "\n").getBytes(StandardCharsets.UTF_8));
}
}
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("visitors", ".log");
save(log, "09:00 Asha", false);
save(log, "09:15 Ravi", false); // overwrite mode: Asha is lost
System.out.print("After overwrite:\n" + Files.readString(log));
save(log, "09:30 Meera", true); // append mode: Ravi is kept
save(log, "09:45 Kabir", true);
System.out.print("After append:\n" + Files.readString(log));
Files.delete(log);
}
}
After overwrite: 09:15 Ravi After append: 09:15 Ravi 09:30 Meera 09:45 Kabir
How the code works
save()opens a newFileOutputStreameach time and passes theappendflag to the constructor.- With
append = false, opening the file empties it first, so Asha's entry is replaced by Ravi's. - With
append = true, Meera and Kabir are added after Ravi. - Try-with-resources closes the stream after every write.
6. Example: Writing a Tiny Image File
An image file is just bytes. This program writes a real 2 × 2 pixel image in the simple PPM format: a short text header followed by three bytes (red, green, blue) per pixel.
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class TinyImageWriter {
public static void main(String[] args) throws IOException {
// A 2 x 2 colour image in the simple binary PPM (P6) format
byte[] header = "P6\n2 2\n255\n".getBytes(StandardCharsets.US_ASCII);
byte[] pixels = {
(byte) 255, 0, 0, 0, (byte) 255, 0, // red, green
0, 0, (byte) 255, (byte) 255, (byte) 255, 0 // blue, yellow
};
Path image = Files.createTempFile("flag", ".ppm");
try (FileOutputStream out = new FileOutputStream(image.toFile())) {
out.write(header); // text header, as bytes
out.write(pixels); // raw RGB bytes
}
System.out.println("Header bytes: " + header.length);
System.out.println("Pixel bytes: " + pixels.length);
System.out.println("File size: " + Files.size(image) + " bytes");
Files.delete(image);
}
}
Header bytes: 11 Pixel bytes: 12 File size: 23 bytes
How the code works
- The header
P6\n2 2\n255\nmeans "binary RGB image, 2 × 2 pixels, colour values up to 255"; it is converted to bytes with US-ASCII. - Values above 127 need a
(byte)cast, because Java'sbytetype ranges from -128 to 127; the file still stores the value 255. - Two
write()calls produce a 23-byte file that most image viewers can open.
7. Common Mistakes and Best Practices
- Accidentally overwriting a file. Pass
trueas the second argument when you want to add data. - Assuming missing folders are created. Only the file is created; create folders with
Files.createDirectories(). - Writing text without a charset. Use
getBytes(StandardCharsets.UTF_8), or aWriter. - Forgetting to close. Use try-with-resources so the file is released.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | FileOutputStream with overwrite constructors. |
| Java 1.1 and 1.4 | Append constructors for String and File; getChannel(). |
| Java 7 | Try-with-resources; Files.newOutputStream() with options such as APPEND and CREATE_NEW. |
| Java 11 | Files.writeString() for writing text in one call. |
| Java 25 | No changes; the class is fully supported. |
9. Summary
FileOutputStreamwrites raw bytes to a file and extendsOutputStream.- By default it replaces the file content;
append = trueadds to the end. - It creates a missing file, but not missing folders.
- It is unbuffered, so wrap it in a
BufferedOutputStreamfor many small writes. - Close it with try-with-resources.
Related Tutorials
- OutputStream Class in Java
- FileInputStream Class in Java
- BufferedOutputStream Class in Java
- FileWriter Class in Java