00:00

Byte Stream in Java: Reading and Writing Binary Data

Last updated:

Photos, PDFs, ZIP archives and audio files are not text: they are sequences of raw bytes that must be copied exactly. Java handles this kind of data with byte streams, the oldest and most fundamental part of the java.io package.

This tutorial explains how byte streams work, the class hierarchy, their key methods and two practical examples.

1. What Is a Byte Stream in Java?

A byte stream reads or writes data one byte (8 bits) at a time, without interpreting it. Every byte stream extends one of two abstract classes:

  • InputStream for reading bytes from a source;
  • OutputStream for writing bytes to a destination.

Because byte streams never change the data, a file copied with them is identical to the original, which makes them the right tool for binary files.

2. Byte Stream Class Hierarchy

Byte stream class hierarchyTwo trees. InputStream, an abstract class since Java 1.0, has subclasses FileInputStream, ByteArrayInputStream, FilterInputStream, ObjectInputStream, PipedInputStream and SequenceInputStream; BufferedInputStream and DataInputStream extend FilterInputStream. OutputStream has subclasses FileOutputStream, ByteArrayOutputStream, FilterOutputStream, ObjectOutputStream and PipedOutputStream; BufferedOutputStream, DataOutputStream and PrintStream extend FilterOutputStream.InputStreamabstract class, Java 1.0FileInputStreamreads a fileByteArrayInputStreamreads a byte[]FilterInputStreamwraps a streamBufferedInputStreambufferingDataInputStreamprimitivesObjectInputStreamobjectsPipedInputStreambetween threadsSequenceInputStreamjoins streamsOutputStreamabstract class, Java 1.0FileOutputStreamwrites a fileByteArrayOutputStreamwrites a byte[]FilterOutputStreamwraps a streamBufferedOutputStreambufferingDataOutputStreamprimitivesPrintStreamformatted textObjectOutputStreamobjectsPipedOutputStreambetween threads

Swipe sideways to see the whole diagram.

Subclasses of FilterInputStream and FilterOutputStream wrap another stream and add a feature, such as buffering or reading Java primitive types.

3. Key Methods of InputStream and OutputStream

MethodDescription
int read()Reads one byte as a value from 0 to 255, or returns -1 at the end of the stream.
int read(byte[] b)Reads up to b.length bytes into the array and returns how many were read, or -1.
byte[] readNBytes(int len)Reads up to len bytes, blocking until they arrive or the stream ends (Java 11).
byte[] readAllBytes()Reads all remaining bytes (Java 9); suitable for small inputs.
long transferTo(OutputStream out)Copies all remaining bytes to an output stream (Java 9).
void write(int b)Writes the low 8 bits of b as one byte.
void write(byte[] b, int off, int len)Writes len bytes from the array, starting at off.
void flush() / void close()Pushes out buffered bytes; releases the underlying resource.

4. Example: Detecting a File Type from Its First Bytes

An upload service cannot trust file extensions: a user might rename a PDF to .jpg. Most formats begin with a fixed byte pattern called a magic number, so reading the first four bytes reveals the real type.

FileSignatureChecker.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HexFormat;

public class FileSignatureChecker {

    // The first bytes of a file ("magic numbers") reveal its real type
    static String detect(byte[] head) {
        String hex = HexFormat.of().formatHex(head);
        if (hex.startsWith("89504e47")) return "PNG image";
        if (hex.startsWith("25504446")) return "PDF document";
        if (hex.startsWith("504b0304")) return "ZIP archive";
        return "unknown";
    }

    public static void main(String[] args) throws IOException {
        byte[][] samples = {
            {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A},    // starts like a PNG
            {'%', 'P', 'D', 'F', '-', '1'},              // starts like a PDF
            {'h', 'e', 'l', 'l', 'o'}                    // plain text
        };
        String[] names = {"avatar.jpg", "invoice.pdf", "notes.dat"};

        for (int i = 0; i < samples.length; i++) {
            Path file = Files.createTempFile("upload", ".bin");
            try (OutputStream out = new FileOutputStream(file.toFile())) {
                out.write(samples[i]);                   // write raw bytes
            }
            try (InputStream in = new FileInputStream(file.toFile())) {
                byte[] head = in.readNBytes(4);          // read exactly the first 4 bytes
                System.out.printf("%-12s %s -> %s%n", names[i], HexFormat.of().formatHex(head), detect(head));
            }
            Files.delete(file);
        }
    }
}
Output
avatar.jpg   89504e47 -> PNG image
invoice.pdf  25504446 -> PDF document
notes.dat    68656c6c -> unknown

How the code works

  1. FileOutputStream.write(byte[]) writes each sample's bytes to a temporary file.
  2. readNBytes(4) reads exactly the first four bytes, or fewer if the file is shorter.
  3. HexFormat (Java 17) formats the bytes as hexadecimal, and detect() compares them with known signatures: PNG files start with 89 50 4E 47 and PDF files with 25 50 44 46 (%PDF).
  4. The file named avatar.jpg is correctly reported as a PNG image, regardless of its extension.

5. Example: Copying a Binary File with a Buffer

A photo app backs up raw image data. This is the classic buffered copy loop, which works for files of any size.

BinaryBackup.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class BinaryBackup {
    public static void main(String[] args) throws IOException {
        Path photo = Files.createTempFile("photo", ".raw");
        byte[] pixels = new byte[10_000];
        for (int i = 0; i < pixels.length; i++) {
            pixels[i] = (byte) (i % 256);                 // fake image data: every byte value 0-255
        }
        Files.write(photo, pixels);

        Path backup = Files.createTempFile("photo-backup", ".raw");
        long total = 0;
        try (InputStream in = new BufferedInputStream(new FileInputStream(photo.toFile()));
             OutputStream out = new BufferedOutputStream(new FileOutputStream(backup.toFile()))) {
            byte[] buffer = new byte[4096];
            int count;
            while ((count = in.read(buffer)) != -1) {     // -1 means end of stream
                out.write(buffer, 0, count);              // write only the bytes actually read
                total += count;
            }
        }

        System.out.println("Bytes copied: " + total);
        System.out.println("Identical copy: " + (Files.mismatch(photo, backup) == -1));   // Java 12
        Files.delete(photo);
        Files.delete(backup);
    }
}
Output
Bytes copied: 10000
Identical copy: true

How the code works

  1. The test data contains every byte value from 0 to 255, which text-based copying could corrupt.
  2. BufferedInputStream and BufferedOutputStream wrap the file streams to reduce disk access.
  3. read(buffer) fills up to 4,096 bytes and returns the count. Writing exactly count bytes matters, because the last read is usually smaller than the buffer.
  4. Files.mismatch() (Java 12) returns -1 when two files are identical.

6. When to Use Byte Streams

Use byte streams forUse character streams for
Images, audio, video, PDFs, ZIP filesPlain text, CSV, JSON, XML, logs
Exact copies of any fileText that must be decoded with a charset
Network protocols and encryptionLine-by-line reading and writing

Reading text through a byte stream and converting each byte to a char breaks non-ASCII characters, because UTF-8 stores them in several bytes. See Character Stream in Java.

7. Common Mistakes and Best Practices

  • Writing the whole buffer. Use write(buffer, 0, count), not write(buffer), or the copy gets extra bytes at the end.
  • Reading one byte at a time without buffering. Wrap file streams in buffered streams, or read into an array.
  • Forgetting to close streams. Use try-with-resources.
  • Using readAllBytes() on huge files. It loads everything into memory; stream large files instead.
  • Treating a byte as unsigned. A Java byte ranges from -128 to 127; read() returns an int from 0 to 255 so that -1 can mean "end of stream".

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0InputStream, OutputStream and the core subclasses.
Java 7Try-with-resources; Files.newInputStream() and Files.newOutputStream().
Java 9readAllBytes(), readNBytes(byte[], int, int) and transferTo().
Java 11readNBytes(int), InputStream.nullInputStream() and OutputStream.nullOutputStream().
Java 12skipNBytes(); Files.mismatch() compares files.
Java 25No new byte stream methods; all of the above are standard.

9. Summary

  • Byte streams read and write raw 8-bit data without changing it.
  • All byte streams extend InputStream or OutputStream.
  • Use them for binary files and exact copies; use character streams for text.
  • Buffer file streams and write only the number of bytes actually read.
  • Java 9+ methods such as readNBytes() and transferTo() remove boilerplate.

Related Tutorials

10. Official Java Documentation References