Character Stream in Java: Reading and Writing Text Correctly
Text looks simple until it contains a rupee sign, an accented letter or an emoji. Files store bytes, but programs work with characters, and something must translate between the two. In Java, that is the job of character streams.
This tutorial explains character streams, their class hierarchy, how charsets turn characters into bytes and two examples that show why the charset matters.
1. What Is a Character Stream in Java?
A character stream reads and writes text as Java char values (16-bit UTF-16 code units) instead of raw bytes. Every character stream extends one of two abstract classes, both added in Java 1.1:
Readerfor reading characters;Writerfor writing characters.
When a character stream is connected to a file or another byte source, it uses a charset, such as UTF-8, to encode characters into bytes when writing and decode bytes into characters when reading.
2. Character Stream Class Hierarchy
Swipe sideways to see the whole diagram.
InputStreamReader and OutputStreamWriter are the bridges between the byte and character worlds; FileReader and FileWriter are convenient subclasses for files.
3. Key Methods of Reader and Writer
| Method | Description |
|---|---|
int read() | Reads one character as an int from 0 to 65535, or -1 at the end. |
int read(char[] cbuf) | Reads characters into an array and returns how many were read, or -1. |
String readLine() | BufferedReader only: one line without its line terminator, or null at the end. |
long transferTo(Writer out) | Copies all remaining characters to a writer (Java 10). |
void write(String str) | Writes a string. |
Writer append(CharSequence csq) | Writes characters and returns the writer, so calls can be chained (Java 5). |
void newLine() | BufferedWriter only: writes the platform line separator. |
void flush() / void close() | Pushes buffered characters out; releases the resource. |
4. How Characters Become Bytes
A charset maps characters to bytes. In UTF-8, the most common charset, English letters use 1 byte, accented letters such as é use 2 bytes, and symbols such as ₹ and € use 3 bytes. A character stream does this conversion automatically, as long as the same charset is used for writing and reading.
5. Example: Writing a Multilingual Cafe Menu
A cafe publishes its menu with prices in rupees and euros. The program writes the menu with a FileWriter and reads it back with a FileReader, both using UTF-8.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class CafeMenuWriter {
public static void main(String[] args) throws IOException {
List<String> menu = List.of("Masala Dosa ₹120", "Crème brûlée €6", "Green tea $2");
Path file = Files.createTempFile("menu", ".txt");
try (BufferedWriter out = new BufferedWriter(new FileWriter(file.toFile(), StandardCharsets.UTF_8))) {
for (String item : menu) {
out.write(item); // characters in, UTF-8 bytes out
out.newLine();
}
}
try (BufferedReader in = new BufferedReader(new FileReader(file.toFile(), StandardCharsets.UTF_8))) {
String line;
int n = 1;
while ((line = in.readLine()) != null) {
int bytes = line.getBytes(StandardCharsets.UTF_8).length;
System.out.println("Item " + n++ + ": " + line.length() + " chars, " + bytes + " bytes, matches: " + menu.contains(line));
}
}
Files.delete(file);
}
}
Item 1: 16 chars, 18 bytes, matches: true Item 2: 15 chars, 20 bytes, matches: true Item 3: 12 chars, 12 bytes, matches: true
How the code works
- The menu uses Unicode escapes such as
\u20B9(₹) so the source file compiles the same way on any system. FileWriterwithStandardCharsets.UTF_8encodes each character into one to three bytes;BufferedWriterbuffers the output.BufferedReader.readLine()decodes the bytes and returns whole lines.- Every line matches the original, while the byte counts show that UTF-8 uses more bytes for non-English characters.
6. Example: What Happens with the Wrong Charset
A shop sign says "Café open". The text is saved as UTF-8 but read back once with UTF-8 and once with ISO-8859-1.
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class CharsetMismatch {
static String readWith(Path file, Charset charset) throws IOException {
StringBuilder text = new StringBuilder();
try (Reader in = Files.newBufferedReader(file, charset)) {
int c;
while ((c = in.read()) != -1) { // read() returns one char, or -1 at the end
text.append((char) c);
}
}
return text.toString();
}
public static void main(String[] args) throws IOException {
String original = "Café open"; // "Cafe open" with an accented e
Path file = Files.createTempFile("sign", ".txt");
try (Writer out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
out.write(original);
}
String right = readWith(file, StandardCharsets.UTF_8);
String wrong = readWith(file, StandardCharsets.ISO_8859_1);
System.out.println("Bytes in file: " + Files.size(file));
System.out.println("Read as UTF-8: " + right.length() + " chars, correct: " + right.equals(original));
System.out.println("Read as ISO-8859-1: " + wrong.length() + " chars, correct: " + wrong.equals(original));
Files.delete(file);
}
}
Bytes in file: 10 Read as UTF-8: 9 chars, correct: true Read as ISO-8859-1: 10 chars, correct: false
How the code works
Files.newBufferedWriter()saves the nine characters as ten bytes, becauseéneeds two bytes in UTF-8.- Reading with UTF-8 combines those two bytes back into one
é. - ISO-8859-1 treats every byte as a separate character, so the text grows to ten characters and the accent turns into two wrong symbols. This garbled text is called mojibake.
7. Common Mistakes and Best Practices
- Relying on the default charset. Before Java 18 it depended on the operating system; pass
StandardCharsets.UTF_8explicitly. - Reading binary files with a
Reader. Decoding images or PDFs as text corrupts them; use byte streams. - Forgetting to flush or close a writer. Buffered text may never reach the file; use try-with-resources.
- Reading one character at a time without buffering. Wrap readers in
BufferedReader.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.1 | Reader, Writer and their subclasses. |
| Java 7 | StandardCharsets; Files.newBufferedReader() and newBufferedWriter(). |
| Java 8 | BufferedReader.lines() returns a stream of lines. |
| Java 10 and 11 | Reader.transferTo(); charset constructors for FileReader and FileWriter; Reader.nullReader() and Writer.nullWriter(). |
| Java 18 | UTF-8 becomes the default charset everywhere (JEP 400). |
| Java 24 | Reader.of(CharSequence) creates a reader over a String; standard in Java 25. |
9. Summary
- Character streams read and write text as characters, not bytes.
- All of them extend
ReaderorWriter. - A charset converts characters to bytes; read with the same charset you wrote with.
- Specify UTF-8 explicitly, and buffer readers and writers.
- Use byte streams for binary files and character streams for text.