Byte Stream vs Character Stream in Java
Java has two kinds of I/O streams, and choosing the wrong one is a classic source of bugs: garbled text, broken images and corrupted downloads. This tutorial compares byte streams and character streams side by side, with two experiments that show exactly what goes wrong when they are mixed up.
1. Byte Streams and Character Streams at a Glance
- A byte stream moves raw 8-bit bytes and never interprets them. Its base classes are
InputStreamandOutputStream. - A character stream moves text as 16-bit
charvalues and uses a charset to convert them to and from bytes. Its base classes areReaderandWriter.
2. How Each Stream Sees Your Data
Swipe sideways to see the whole diagram.
Underneath, every file contains bytes. A character stream adds a translation layer on top; a byte stream does not.
3. Byte Stream vs Character Stream: Comparison
| Aspect | Byte stream | Character stream |
|---|---|---|
| Base classes | InputStream, OutputStream | Reader, Writer |
| Unit of data | 8-bit byte | 16-bit char |
| Charset handling | None; bytes pass through unchanged | Encodes and decodes using a charset |
read() returns | 0 to 255, or -1 | 0 to 65535, or -1 |
| Line-based reading | Not available | BufferedReader.readLine() |
| Introduced | Java 1.0 | Java 1.1 |
| Best for | Images, audio, PDFs, ZIP files, exact copies | Text, CSV, JSON, XML, logs |
4. Example: Reading a Price Tag Both Ways
A billing screen saves a total that includes the rupee sign (₹) and then reads it back, once with a byte stream and once with a character stream.
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class PriceTagReader {
public static void main(String[] args) throws IOException {
String price = "Total: ₹499"; // "Total: Rs 499" with the rupee sign
Path file = Files.createTempFile("price", ".txt");
Files.writeString(file, price); // saved as UTF-8
// Byte stream: every byte becomes a char (wrong for text)
StringBuilder viaBytes = new StringBuilder();
try (InputStream in = Files.newInputStream(file)) {
int b;
while ((b = in.read()) != -1) {
viaBytes.append((char) b);
}
}
// Character stream: bytes are decoded with UTF-8
StringBuilder viaChars = new StringBuilder();
try (Reader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
int c;
while ((c = in.read()) != -1) {
viaChars.append((char) c);
}
}
System.out.println("Byte stream: " + viaBytes.length() + " values, text correct: " + viaBytes.toString().equals(price));
System.out.println("Character stream: " + viaChars.length() + " values, text correct: " + viaChars.toString().equals(price));
Files.delete(file);
}
}
Byte stream: 13 values, text correct: false Character stream: 11 values, text correct: true
How the code works
Files.writeString()stores the 11 characters as 13 bytes, because₹takes three bytes in UTF-8.- The byte stream turns each byte into a separate
char, splitting the rupee sign into three meaningless characters. - The character stream decodes the three bytes together and rebuilds the original text exactly.
5. Example: Copying a Binary File Both Ways
Now the opposite mistake: copying binary data, such as an icon, through character streams.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class BinaryCopyTrap {
public static void main(String[] args) throws IOException {
byte[] data = new byte[256];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) i; // every possible byte value, like an image
}
Path original = Files.createTempFile("icon", ".bin");
Files.write(original, data);
Path byteCopy = Files.createTempFile("copy-bytes", ".bin");
try (InputStream in = Files.newInputStream(original); OutputStream out = Files.newOutputStream(byteCopy)) {
in.transferTo(out);
}
Path charCopy = Files.createTempFile("copy-chars", ".bin");
try (Reader in = new InputStreamReader(Files.newInputStream(original), StandardCharsets.UTF_8);
Writer out = new OutputStreamWriter(Files.newOutputStream(charCopy), StandardCharsets.UTF_8)) {
in.transferTo(out); // decodes and re-encodes as if it were text
}
System.out.println("Original size: " + Files.size(original) + " bytes");
System.out.println("Byte stream copy: " + Files.size(byteCopy) + " bytes, identical: " + (Files.mismatch(original, byteCopy) == -1));
System.out.println("Char stream copy: " + Files.size(charCopy) + " bytes, identical: " + (Files.mismatch(original, charCopy) == -1));
Files.delete(original);
Files.delete(byteCopy);
Files.delete(charCopy);
}
}
Original size: 256 bytes Byte stream copy: 256 bytes, identical: true Char stream copy: 512 bytes, identical: false
How the code works
- The test file contains all 256 byte values, as real images do.
- The byte stream copy uses
transferTo()and is identical to the original. - The character stream decodes the bytes as UTF-8. On JDK 25,
InputStreamReaderreplaced each of the 128 bytes that are not valid UTF-8 with the replacement characterU+FFFD, which takes 3 bytes when written back, so the copy doubled to 512 bytes and the data was lost. - Readers created with
Files.newBufferedReader()are stricter: they throw anIOException(MalformedInputException) instead of silently replacing bytes.
6. Converting Between the Two
Sometimes you receive bytes but need text, for example from a network socket. Two bridge classes connect the families:
| Class | Converts | Example |
|---|---|---|
InputStreamReader | Bytes to characters | new InputStreamReader(socket.getInputStream(), UTF_8) |
OutputStreamWriter | Characters to bytes | new OutputStreamWriter(out, UTF_8) |
Always pass the charset explicitly so the conversion is predictable.
7. Which One Should You Use?
- If the data is text and you need to read or change it, use a character stream with UTF-8.
- If the data is binary, or you only need to move or copy it, use a byte stream.
- If you only need the whole content of a small file,
Files.readString()orFiles.readAllBytes()is simpler.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 and 1.1 | Byte streams first; character streams added in 1.1 to handle text correctly. |
| Java 9 and 10 | InputStream.transferTo() and Reader.transferTo(). |
| Java 11 | Files.readString() and writeString(); charset constructors for FileReader and FileWriter. |
| Java 18 | UTF-8 is the default charset on every platform (JEP 400). |
| Java 25 | No new stream types; the comparison above applies unchanged. |
9. Summary
- Byte streams move raw bytes; character streams move text and use a charset.
- Reading text through a byte stream breaks multi-byte characters.
- Copying binary data through a character stream corrupts it.
InputStreamReaderandOutputStreamWriterbridge the two families.- Specify UTF-8 explicitly whenever you convert between bytes and text.