[post-views]
In this lesson, you will learn.
The following is the I/O stream hierarchy.

In Java, byte streams are used to perform input and output of bytes or binary data, making them very useful for handling raw binary data and files such as images, audio files, and any other binary data files.
The following are the two primary byte stream classes

Below is an example demonstrating that reading from one file and writing to another using byte streams in Java. This example effectively copies a file.
package bytestream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
/* Using try-with-resources to ensure that all resources
* will be closed automatically */
try (FileInputStream in = new FileInputStream
("src/bytestream/file1.txt");
FileOutputStream out = new FileOutputStream
("src/bytestream/file2.txt")) {
int byteRead;
// Read a single byte at a time and write it to the output file
while ((byteRead = in.read()) != -1) {
out.write(byteRead);
}
System.out.println("File has been copied.");
} catch (IOException e) {
System.out.println("Error occurred:");
e.printStackTrace();
}
}
}
Output
File has been copied.
Byte streams in Java handle I/O of raw binary data. They read or write data byte by byte, which makes them suitable for handling all types of data, including binary files (like images, audio files, etc.) and textual data.
Character streams handle the I/O of characters, automatically taking character encoding into account. They read or write data character by character.
This abstraction is beneficial when dealing with textual data as it seamlessly handles character encoding, converting internally between characters and bytes.
Thus, character streams are preferred when working with text files.
| Aspect | Byte Streams | Character Streams |
|---|---|---|
| Data Handling | Handle 8-bit bytes | Handle 16-bit Unicode characters |
| Use Case | Best for binary data (e.g., files, images, audio) | Best for text data, taking care of character encoding |
| Performance | Read/write data exactly as it appears in the file (binary form) | Potentially slower due to encoding and decoding steps |
| Convenience | Requires manual handling of character encoding if used for text | Automatically handles character encoding and decoding |
| Buffering | External buffering needed (via BufferedInputStream / BufferedOutputStream) |
Built-in buffering options (BufferedReader / BufferedWriter) |
| Method of Operation | Operates directly on binary data | Operates on characters, translating to/from byte stream as needed |
Nice
You must be logged in to submit a review.