C

Core Java tutorial for beginners

Clean • Professional

Binary File I/O in Java Using FileInputStream and FileOutputStream

3 minute

Binary File I/O in Java (FileInputStream & FileOutputStream)

Binary File I/O in Java is used to read and write raw bytes, making it suitable for non-text files such as images, videos, audio files, executables, PDFs, and ZIP archives. Unlike text data, binary data must be handled using byte streams; using character streams (FileReader, BufferedReader) corrupts binary content.


What Are Binary Files?

Binary files store data exactly as bytes (0–255). These files are not human-readable and cannot be processed using character-based classes.

Examples of Binary Files

  • Images → .jpg, .png, .gif
  • Videos → .mp4, .mkv
  • Audio → .mp3, .wav
  • Documents → .pdf, .docx
  • Compressed files → .zip, .rar
  • Executables → .exe
  • Serialized Java objects → .ser

Because these files contain raw bytes, Java requires byte-based streams for safe reading and writing.


Binary I/O Streams in Java

Java provides two important classes from java.io package:

learn code with durgesh images

  • FileInputStream — Reads bytes from a file
  • FileOutputStream — Writes bytes to a file

Both operate strictly on byte data, making them ideal for binary files.


1. Reading Binary Files using FileInputStream

How FileInputStream Works

  • Reads data byte-by-byte
  • Returns integer values from 0 to 255
  • Returns 1 when end of file is reached
  • Does not perform character conversion → safe for all binary formats

Example: Read a binary file byte by byte

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryFile {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("image.jpg")) {

            int data;
            while ((data = fis.read()) != -1) {
                System.out.print(data + " ");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


2. Writing Binary Files using FileOutputStream

How FileOutputStream Works

  • Writes data byte-by-byte
  • Can overwrite or append to a file
  • No encoding conversion

Example: Write bytes to a binary file

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteBinaryFile {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("output.bin")) {

            byte[] data = {10, 20, 30, 40, 50};
            fos.write(data);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


3. Copying a Binary File (Most Realistic Use Case)

Copying files like images, videos, and PDFs is the most common binary I/O operation.

Example: Fast binary file copying using buffer

import java.io.*;

public class CopyBinaryFile {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("source.jpg");
             FileOutputStream fos = new FileOutputStream("copy.jpg")) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("File copied successfully!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Why Buffering Is Used?

  • Faster reading and writing
  • Reduces number of I/O calls
  • Prevents performance issues with large files

Key Methods of FileInputStream & FileOutputStream

MethodDescription
read()Reads a single byte, returns int (0–255)
read(byte[])Reads multiple bytes into an array
write(int)Writes a single byte
write(byte[])Writes a byte array
close()Closes the stream

Why Use Byte Streams for Binary Files?

Text File Handling (Character Streams)Binary File Handling (Byte Streams)
Works with Unicode charactersWorks with raw bytes
Converts data (may corrupt binary files)No conversion → safe for binary data
Uses FileReader, BufferedReaderUses FileInputStream, FileOutputStream
Suitable for .txt, .csvSuitable for .jpg, .mp4, .pdf

Common Mistakes to Avoid

  • Using FileReader to read binary files → Causes corruption because of character conversion
  • Printing raw bytes expecting readable text → Bytes are not printable characters
  • Avoid reading byte-by-byte for large files → Always use a buffer for high performance

Points to Remember

  • Binary files contain raw bytes
  • Use FileInputStream for reading
  • Use FileOutputStream for writing
  • Always use buffer (byte[]) for performance
  • Character streams are not suitable for binary data
  • Works for images, videos, PDFs, ZIPs, audio, etc.

Article 0 of 0