All 15 I/O & NIO questions
More in I/O & NIO
Advertisement
Back to results for “I/O Streams”
Java › I/O & NIO

What is the difference between byte streams (InputStream/OutputStream) and character streams (Reader/Writer) in the classic java.io package?

Beginner

Answer

Byte streams (InputStream/OutputStream) work with raw 8-bit bytes, appropriate for binary data (images, serialized objects, arbitrary binary files) where no text encoding interpretation is meaningful; character streams (Reader/Writer) work with 16-bit Unicode characters, handling the necessary encoding/decoding between raw bytes and actual text characters (via a specified or platform-default Charset), appropriate whenever you're working with genuine textual data, since using a byte stream directly for text would require you to manually handle character encoding yourself, a common source of subtle bugs with non-ASCII text.
// Byte stream: for binary data
try (InputStream in = new FileInputStream("image.png")) {
    byte[] buffer = new byte[1024];
    int bytesRead = in.read(buffer);
}

// Character stream: for text data, handles encoding automatically
try (Reader reader = new InputStreamReader(new FileInputStream("text.txt"), StandardCharsets.UTF_8)) {
    int character = reader.read();  // reads a decoded Unicode character, not a raw byte
}
Real-world example A file-processing utility correctly distinguishes between reading a PNG image (using FileInputStream directly for raw bytes) and reading a UTF-8 encoded text configuration file (using an InputStreamReader wrapping a FileInputStream, explicitly specifying UTF-8), avoiding the encoding-related bugs that would occur from treating the text file as raw, un-decoded bytes.

Common follow-ups: What happens if you read multi-byte UTF-8 encoded text using a raw byte stream without proper decoding?;Why does the JDK provide both a byte-stream and character-stream class hierarchy instead of just one unified approach?