Java FileOutputStream

Introduction

Writing data to files is one of the most important features of Java programming. Applications frequently need to save user information, generate reports, create log files, store images, export documents, or write binary data. Java provides several classes for writing data, and one of the most fundamental classes is FileOutputStream.

The FileOutputStream class belongs to the java.io package and is used to write raw bytes to a file. Unlike FileWriter, which writes characters, FileOutputStream works with bytes, making it the preferred choice for writing binary files such as images, PDF documents, audio files, videos, ZIP archives, and executable files.

Although FileOutputStream can also write text data by converting characters into bytes, it is generally recommended to use FileWriter or BufferedWriter for writing text files because they handle character encoding more effectively.

What is FileOutputStream?

FileOutputStream is a Java class used to write data to a file as a stream of bytes.

Package:


import java.io.FileOutputStream;

It is commonly used for writing:

  • Images
  • PDF files
  • Audio files
  • Video files
  • ZIP files
  • Binary application data

Since all files are ultimately stored as bytes, FileOutputStream provides a low-level mechanism for writing any type of file.

Why Use FileOutputStream?

FileOutputStream offers several advantages:

  • Writes raw byte data
  • Supports binary files
  • Works with all file types
  • Can write individual bytes or byte arrays
  • Integrates with buffered streams for improved performance

It is widely used in applications such as document management systems, file upload services, multimedia applications, and backup tools.

How FileOutputStream Works?

When a FileOutputStream object is created, Java opens the specified file for writing.

If the file does not exist, Java creates it automatically.

If the file already exists, its contents are overwritten unless append mode is enabled.

The write() methods send bytes to the file. After writing is complete, the stream should be closed to ensure all data is saved and system resources are released.

Creating a FileOutputStream

The simplest way to create a FileOutputStream is by specifying the file name.

Syntax


FileOutputStream output =
    new FileOutputStream("sample.bin");

This creates or opens the file for writing.

Writing a Single Byte

The write(int b) method writes one byte at a time.

Example


import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        try {
            FileOutputStream output =
                new FileOutputStream("letters.txt");
            output.write(65);
            output.write(66);
            output.write(67);
            output.close();
            System.out.println("Data written successfully.");
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

Output

Data written successfully.

The file contains:


ABC

The numbers 65, 66, and 67 represent the ASCII values of A, B, and C.

Writing a Byte Array

Writing multiple bytes at once is more efficient.

Example


import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        try {
            FileOutputStream output =
                new FileOutputStream("message.txt");
            byte[] data =
                "Hello Java".getBytes();
            output.write(data);
            output.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

Output

Hello Java

Appending Data to a File

By default, FileOutputStream overwrites existing data.

To append data, use the second constructor parameter.


FileOutputStream output =
    new FileOutputStream("message.txt", true);
output.write("\nWelcome!".getBytes());
output.close();

The new text is added to the end of the existing file.

Writing Binary Files

FileOutputStream is ideal for writing binary files.

Example


import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        try {
            FileOutputStream output =
                new FileOutputStream("image_copy.png");
            byte[] imageData = new byte[1024];
            // Image bytes would typically be read from another source
            output.write(imageData);
            output.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

This approach is commonly used when copying or generating binary files.

Common FileOutputStream Methods

write(int b)

Writes one byte.


output.write(65);

write(byte[])

Writes an entire byte array.


output.write(data);

write(byte[], int, int)

Writes a specified portion of a byte array.


output.write(data, 0, 5);

This writes the first five bytes.

flush()

Forces buffered data to be written immediately.


output.flush();

Although FileOutputStream writes directly, flush() is particularly useful when the stream is wrapped by buffered output classes.

close()

Closes the stream and releases system resources.


output.close();

Always close the stream after writing.

Using try-with-resources (Recommended)

The recommended approach is try-with-resources.


import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        try (FileOutputStream output =
                new FileOutputStream("message.txt")) {
            output.write("Java FileOutputStream".getBytes());
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

The stream is automatically closed, even if an exception occurs.

FileOutputStream vs FileWriter

FileOutputStream FileWriter
Writes bytes Writes characters
Suitable for binary files Suitable for text files
Does not handle character encoding Handles character encoding
Used for images, PDFs, ZIP files Used for text documents
Low-level byte stream Character stream

Use FileOutputStream for binary data and FileWriter for text.

FileOutputStream vs BufferedOutputStream

FileOutputStream BufferedOutputStream
Writes directly to the file Uses an internal buffer
Slower for frequent small writes Faster due to buffering
Suitable for simple tasks Better for large files

BufferedOutputStream is commonly used to improve performance when writing large amounts of data.

Real-Life Example

Suppose you are building a file backup application.


import java.io.FileOutputStream;
import java.io.IOException;
public class BackupSystem {
    public static void main(String[] args) {
        try (FileOutputStream output =
                new FileOutputStream("backup.dat")) {
            byte[] backupData =
                "Backup Completed Successfully"
                    .getBytes();
            output.write(backupData);
            System.out.println("Backup saved.");
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

Applications that generate backups, reports, or downloadable documents frequently use FileOutputStream.

Advantages of FileOutputStream

  • Supports binary file writing
  • Works with any file type
  • Easy to use
  • Can write single bytes or byte arrays
  • Integrates with buffered streams
  • Suitable for low-level file operations

Limitations of FileOutputStream

  • Does not handle character encoding automatically
  • Not ideal for writing text files
  • Slower than buffered output streams for frequent small writes
  • Requires exception handling

Common Mistakes

1. Using FileOutputStream for Text Files

Incorrect:


FileOutputStream output =
    new FileOutputStream("students.txt");

While this works, use FileWriter or BufferedWriter for text because they handle character encoding more appropriately.

2. Forgetting to Close the Stream

Incorrect:


FileOutputStream output =
    new FileOutputStream("sample.bin");

Correct:


output.close();

Or use try-with-resources.

3. Accidentally Overwriting Existing Data

Incorrect:


new FileOutputStream("message.txt");

Correct:


new FileOutputStream("message.txt", true);

Enable append mode when you need to preserve existing content.

4. Writing One Byte at a Time for Large Files

Instead of:


output.write(65);

Prefer:


output.write(byteArray);

Writing byte arrays is more efficient for larger amounts of data.

Best Practices

📖
Best Practices:
  • Use FileOutputStream for binary files.
  • Use BufferedInputStream for better performance with large files.
  • Write byte arrays instead of single bytes whenever possible.
  • Always use try-with-resources.
  • Handle exceptions properly.
  • Use FileWriter or BufferedWriter for character-based text outpu
  • Close streams promptly to release system resources.

Conclusion

The Java FileOutputStream class is a core part of Java’s I/O framework for writing binary data to files. It provides a simple and flexible way to write bytes, making it the preferred choice for handling images, PDF documents, multimedia files, ZIP archives, and other binary content. It also supports writing byte arrays efficiently and can be combined with BufferedOutputStream for better performance.

Related Java Tutorials