← Back to Chapters

Java Byte Streams

? Java Byte Streams

? Quick Overview

Byte Streams in Java are used to perform input and output of raw binary data. They handle data in the form of bytes (8-bit) and are mainly used for files, images, audio, video, and other non-text data.

? Key Concepts

  • Byte streams work with 8-bit bytes
  • Root classes: InputStream and OutputStream
  • Suitable for binary files
  • Reads and writes one byte at a time

? Syntax / Theory

Java provides several subclasses of byte streams such as FileInputStream and FileOutputStream to read and write data from files.

? Code Example(s)

? View Code Example
// Writing bytes to a file using FileOutputStream
import java.io.FileOutputStream;

public class WriteByteExample {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("data.bin");
fos.write(65);
fos.write(66);
fos.write(67);
fos.close();
}
}
? View Code Example
// Reading bytes from a file using FileInputStream
import java.io.FileInputStream;

public class ReadByteExample {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("data.bin");
int value;
while ((value = fis.read()) != -1) {
System.out.println(value);
}
fis.close();
}
}

? Live Output / Explanation

Explanation

In the writing example, numeric byte values are stored in a file. In the reading example, bytes are read one by one until the end of the file is reached (-1).

? Interactive Simulator

Type below to visualize how characters are converted into an 8-bit Byte Stream (ASCII values).

Byte stream waiting for input...

This mimics how OutputStream.write() sees your data.

✅ Tips & Best Practices

  • Always close streams to free system resources
  • Use byte streams for binary data only
  • Wrap streams with buffers for better performance

? Try It Yourself

  • Write a program to copy an image using byte streams
  • Modify the example to store user input as bytes
  • Experiment with BufferedInputStream