Introduction
In Java, streams are used to read and write data. There are two types of streams: Byte Stream and Character Stream. These streams help in handling data efficiently, whether it is from a file, network, or another source.

In this article, we will discuss what byte streams and character streams are, how they work, their differences, and when to use each of them with examples.
What is Byte Stream in Java?
A Byte Stream in Java is used to handle input and output of raw binary data. It reads and writes data in bytes (8-bit data), making it suitable for handling audio, video, and image files. It uses InputStream and OutputStream classes to perform these operations.
Benefits of Byte Stream
Byte Stream in Java is used to handle binary data. It reads & writes data in the form of bytes, which makes it ideal for working with files like images, audio, videos, or any non-text data. Let’s take a look at the some key benefits of using Byte Stream:
1. Universal Data Handling: Byte Stream can process any type of data, whether it’s text, images, or audio. This makes it highly versatile.
2. Efficiency: Since Byte Stream works directly with raw bytes, it’s faster & more efficient for handling large files or binary data.
3. Low-Level Operations: It provides fine-grained control over data, allowing you to manipulate individual bytes.
Example of Byte Stream in Java
Let’s look at a simple example where we use Byte Stream to read & write data from a file. We’ll use `FileInputStream` to read bytes from a file & `FileOutputStream` to write bytes to a file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
// File paths
String inputFile = "input.txt";
String outputFile = "output.txt";
// Using try-with-resources to automatically close streams
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile)) {
int byteData;
// Read bytes from input file & write to output file
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
System.out.println("File copied successfully using Byte Stream!");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
In this Code:
1. FileInputStream: This class reads data from a file in the form of bytes. In the example, it reads from `input.txt`.
2. FileOutputStream: This class writes data to a file in the form of bytes. In the example, it writes to `output.txt`.
3. try-with-resources: This ensures that the streams are automatically closed after the operation, preventing resource leaks.
4. fis.read(): This method reads one byte at a time from the file. It returns `-1` when the end of the file is reached.
5. fos.write(): This method writes one byte at a time to the output file.