00:00

FileOutputStream Class in Java: Writing Bytes to a File

Last updated:

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 BufferedOutputStream when writing many small pieces.

2. FileOutputStream Class Hierarchy

FileOutputStream class hierarchyFileOutputStream extends the abstract class OutputStream, which extends Object. It implements Closeable, Flushable and AutoCloseable. With append set to false it replaces the file content, with append set to true it adds to the end, and a missing file is created.ObjectextendsOutputStreamabstract classextendsFileOutputStreamwrites raw bytes to a fileCloseableFlushableAutoCloseableimplementsOpening modesappend = false replaceappend = true add to endmissing file created

Swipe sideways to see the whole diagram.

3. Constructors of FileOutputStream

ConstructorDescription
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

MethodDescription
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.

VisitorLog.java
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);
    }
}
Output
After overwrite:
09:15 Ravi
After append:
09:15 Ravi
09:30 Meera
09:45 Kabir

How the code works

  1. save() opens a new FileOutputStream each time and passes the append flag to the constructor.
  2. With append = false, opening the file empties it first, so Asha's entry is replaced by Ravi's.
  3. With append = true, Meera and Kabir are added after Ravi.
  4. 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.

TinyImageWriter.java
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);
    }
}
Output
Header bytes: 11
Pixel bytes:  12
File size:    23 bytes

How the code works

  1. The header P6\n2 2\n255\n means "binary RGB image, 2 × 2 pixels, colour values up to 255"; it is converted to bytes with US-ASCII.
  2. Values above 127 need a (byte) cast, because Java's byte type ranges from -128 to 127; the file still stores the value 255.
  3. 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 true as 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 a Writer.
  • Forgetting to close. Use try-with-resources so the file is released.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0FileOutputStream with overwrite constructors.
Java 1.1 and 1.4Append constructors for String and File; getChannel().
Java 7Try-with-resources; Files.newOutputStream() with options such as APPEND and CREATE_NEW.
Java 11Files.writeString() for writing text in one call.
Java 25No changes; the class is fully supported.

9. Summary

  • FileOutputStream writes raw bytes to a file and extends OutputStream.
  • By default it replaces the file content; append = true adds to the end.
  • It creates a missing file, but not missing folders.
  • It is unbuffered, so wrap it in a BufferedOutputStream for many small writes.
  • Close it with try-with-resources.

Related Tutorials

10. Official Java Documentation References