00:00

Character Stream in Java: Reading and Writing Text Correctly

Last updated:

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:

  • Reader for reading characters;
  • Writer for 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

Character stream class hierarchyTwo trees. Reader, an abstract class since Java 1.1, has subclasses BufferedReader, InputStreamReader, StringReader, CharArrayReader, PipedReader and FilterReader; FileReader extends InputStreamReader. Writer has subclasses BufferedWriter, OutputStreamWriter, StringWriter, PrintWriter, CharArrayWriter and PipedWriter; FileWriter extends OutputStreamWriter.Readerabstract class, Java 1.1BufferedReaderlines, bufferingInputStreamReaderbytes to charsFileReaderreads a fileStringReaderreads a StringCharArrayReaderreads a char[]PipedReaderbetween threadsFilterReaderwraps a readerWriterabstract class, Java 1.1BufferedWriterbufferingOutputStreamWriterchars to bytesFileWriterwrites a fileStringWriterbuilds a StringPrintWriterformatted textCharArrayWriterbuilds a char[]PipedWriterbetween threads

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

MethodDescription
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.

CafeMenuWriter.java
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);
    }
}
Output
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

  1. The menu uses Unicode escapes such as \u20B9 (₹) so the source file compiles the same way on any system.
  2. FileWriter with StandardCharsets.UTF_8 encodes each character into one to three bytes; BufferedWriter buffers the output.
  3. BufferedReader.readLine() decodes the bytes and returns whole lines.
  4. 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.

CharsetMismatch.java
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);
    }
}
Output
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

  1. Files.newBufferedWriter() saves the nine characters as ten bytes, because é needs two bytes in UTF-8.
  2. Reading with UTF-8 combines those two bytes back into one é.
  3. 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_8 explicitly.
  • 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 versionChange
Java 1.1Reader, Writer and their subclasses.
Java 7StandardCharsets; Files.newBufferedReader() and newBufferedWriter().
Java 8BufferedReader.lines() returns a stream of lines.
Java 10 and 11Reader.transferTo(); charset constructors for FileReader and FileWriter; Reader.nullReader() and Writer.nullWriter().
Java 18UTF-8 becomes the default charset everywhere (JEP 400).
Java 24Reader.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 Reader or Writer.
  • 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.

Related Tutorials

10. Official Java Documentation References