Byte Stream in Java: Reading and Writing Binary Data
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:
InputStreamfor reading bytes from a source;OutputStreamfor 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
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
| Method | Description |
|---|---|
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.
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);
}
}
}
avatar.jpg 89504e47 -> PNG image invoice.pdf 25504446 -> PDF document notes.dat 68656c6c -> unknown
How the code works
FileOutputStream.write(byte[])writes each sample's bytes to a temporary file.readNBytes(4)reads exactly the first four bytes, or fewer if the file is shorter.HexFormat(Java 17) formats the bytes as hexadecimal, anddetect()compares them with known signatures: PNG files start with89 50 4E 47and PDF files with25 50 44 46(%PDF).- The file named
avatar.jpgis 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.
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);
}
}
Bytes copied: 10000 Identical copy: true
How the code works
- The test data contains every byte value from 0 to 255, which text-based copying could corrupt.
BufferedInputStreamandBufferedOutputStreamwrap the file streams to reduce disk access.read(buffer)fills up to 4,096 bytes and returns the count. Writing exactlycountbytes matters, because the last read is usually smaller than the buffer.Files.mismatch()(Java 12) returns-1when two files are identical.
6. When to Use Byte Streams
| Use byte streams for | Use character streams for |
|---|---|
| Images, audio, video, PDFs, ZIP files | Plain text, CSV, JSON, XML, logs |
| Exact copies of any file | Text that must be decoded with a charset |
| Network protocols and encryption | Line-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), notwrite(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
byteranges from -128 to 127;read()returns anintfrom 0 to 255 so that-1can mean "end of stream".
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | InputStream, OutputStream and the core subclasses. |
| Java 7 | Try-with-resources; Files.newInputStream() and Files.newOutputStream(). |
| Java 9 | readAllBytes(), readNBytes(byte[], int, int) and transferTo(). |
| Java 11 | readNBytes(int), InputStream.nullInputStream() and OutputStream.nullOutputStream(). |
| Java 12 | skipNBytes(); Files.mismatch() compares files. |
| Java 25 | No 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
InputStreamorOutputStream. - 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()andtransferTo()remove boilerplate.
Related Tutorials
- Java I/O Streams
- InputStream Class in Java
- OutputStream Class in Java
- Byte Stream vs Character Stream