DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

How Java reads and writes text: bytes, characters, and encoding

How Java reads and writes text: bytes, characters, and encoding

byte[] bytes = {79, 108, -61, -95};
System.out.println(new String(bytes));

Enter fullscreen mode Exit fullscreen mode

What does this print? On a machine where the platform default charset is UTF-8, it prints Olá. On a machine with ISO-8859-1 as the default, it prints Olá. Same four bytes, two different strings. That's the encoding problem in one example, and it's what this part is about.

InputStream: the byte contract

InputStream represents a source of bytes. The core method is:

public abstract int read() throws IOException;

Enter fullscreen mode Exit fullscreen mode

It returns a single byte as an int in the range 0 to 255, or -1 when the stream is exhausted.

Why int and not byte? A Java byte is signed, so its range is -128 to 127. The value 255, a perfectly valid byte, would be -1 when stored in a byte variable — the same value as the end-of-stream sentinel. Using int avoids that collision: data bytes come back as 0–255, and -1 is unambiguous.

Reading from a file one byte at a time:

try (InputStream in = new FileInputStream("data.bin")) {
    int b;
    while ((b = in.read()) != -1) {
        process(b); // b is 0–255
    }
}

Enter fullscreen mode Exit fullscreen mode

This is the right tool for binary files: images, compressed data, raw network bytes. For text, there's a better abstraction.

Reader: the character contract

Reader represents a source of characters. Its core method mirrors InputStream:

public int read() throws IOException;

Enter fullscreen mode Exit fullscreen mode

It returns a character as an int in the range 0 to 65535 (the Unicode Basic Multilingual Plane), or -1 at end of stream. The same int trick applies: a Java char is unsigned and covers 0–65535, so -1 is an unambiguous sentinel.

Reading text:

try (Reader reader = new FileReader("message.txt")) {
    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);
    }
}

Enter fullscreen mode Exit fullscreen mode

This reads characters. But there is a problem hidden in new FileReader("message.txt") — we'll get there in a moment.

What encoding is

A charset maps byte sequences to characters. UTF-8 encodes the character 'O' (U+004F) as the single byte 0x4F. It encodes 'á' (U+00E1) as two bytes: 0xC3 0xA1. ISO-8859-1 encodes 'á' as the single byte 0xE1.

Back to the opening example. The four bytes {79, 108, -61, -95} are, in hex, {4F, 6C, C3, A1}. In UTF-8, C3 A1 is the two-byte sequence for 'á', so the four bytes decode to Olá. In ISO-8859-1, C3 decodes to 'Ã' and A1 decodes to '¡', giving Olá.

The bytes didn't change. The interpretation did.

This is why new String(bytes) is unreliable. It calls new String(bytes, Charset.defaultCharset()), which depends on whatever charset the JVM was started with.

InputStreamReader: explicit charset

InputStreamReader wraps an InputStream and decodes its bytes into characters using a named charset:

try (InputStream in = new FileInputStream("message.txt");
     Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);
    }
}

Enter fullscreen mode Exit fullscreen mode

StandardCharsets.UTF_8 is a constant in java.nio.charset.StandardCharsets, available since Java 7. The class holds constants for UTF-8, UTF-16, ISO-8859-1, US-ASCII, and two UTF-16 variants. For modern files and network data, UTF-8 is almost always the right choice.

What InputStreamReader does internally: it reads bytes from the underlying InputStream and groups them according to the charset's rules. For UTF-8, it reads multi-byte sequences and produces one char per decoded code point (or two chars for characters outside the BMP, as a surrogate pair). For ISO-8859-1, it treats every byte as one character.

The FileReader default charset

FileReader is a convenience class that wraps FileInputStream with an InputStreamReader. Before Java 11, its only constructor took a file name or a File:

// Java 1.1 to Java 10: no way to specify charset
Reader reader = new FileReader("message.txt"); // uses Charset.defaultCharset()

Enter fullscreen mode Exit fullscreen mode

The platform default was set by the OS locale. On Linux and macOS with a UTF-8 locale it was UTF-8. On Windows it was typically Windows-1252 for Western European locales. Code that worked on one machine could silently produce wrong results on another.

Java 11 added a charset-accepting constructor:

// Java 11+
Reader reader = new FileReader("message.txt", StandardCharsets.UTF_8);

Enter fullscreen mode Exit fullscreen mode

Use this form. The overload without a charset exists for backward compatibility, not convenience.

Java 18 changed the default

JEP 400, shipped in Java 18, made UTF-8 the default charset on all platforms. Before Java 18, Charset.defaultCharset() returned whatever the OS locale specified. From Java 18 it returns UTF-8 regardless of the platform, unless you override it with a system property at startup.

What changes for existing code? Code that called new FileReader(file) and expected the platform locale's charset for correct decoding now decodes as UTF-8. If the files actually contain UTF-8, the behavior is the same. If they contain Windows-1252 or ISO-8859-1 and the code relied on the system default, it now produces wrong output.

Explicit charset arguments are unaffected by this change. That's another reason to prefer them.

OutputStream and Writer

The write side is symmetric. OutputStream.write(int b) writes one byte (the low 8 bits of the int). Writer.write(int c) writes one character. OutputStreamWriter connects the two, encoding chars to bytes using a specified charset:

try (OutputStream out = new FileOutputStream("output.txt");
     Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
    writer.write("Olá");
}

Enter fullscreen mode Exit fullscreen mode

writer.write("Olá") encodes the three Unicode characters to four UTF-8 bytes and passes them to the underlying OutputStream.

FileWriter is the write-side equivalent of FileReader, with the same default-charset problem and the same Java 11 fix:

// Java 11+
Writer writer = new FileWriter("output.txt", StandardCharsets.UTF_8);

Enter fullscreen mode Exit fullscreen mode

Buffering

Each call to InputStream.read() or Writer.write(char) goes to the OS. For a file, that's a system call per byte. Reading a 1 MB text file one byte at a time means roughly a million system calls; it's slow regardless of disk speed.

BufferedInputStream and BufferedReader solve this by reading a block of bytes from the OS per request and holding the extras in memory. The default buffer size for both is 8192 bytes in OpenJDK.

For reading text with explicit charset and line-by-line access, the layers stack like this:

try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            new FileInputStream("message.txt"),
            StandardCharsets.UTF_8))) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}

Enter fullscreen mode Exit fullscreen mode

BufferedReader.readLine() returns one line at a time, stripping the line terminator (\n, \r\n, or \r). It returns null at end of stream. For the common case of reading a named file, Files.newBufferedReader does the same stacking in one call:

try (BufferedReader reader = Files.newBufferedReader(
        Path.of("message.txt"), StandardCharsets.UTF_8)) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}

Enter fullscreen mode Exit fullscreen mode

Files.newBufferedReader is available since Java 7 as part of NIO.2.

For small files: Files.readString

If the file fits in memory, Files.readString (Java 11+) is simpler:

String content = Files.readString(Path.of("message.txt"), StandardCharsets.UTF_8);

Enter fullscreen mode Exit fullscreen mode

One call. The charset is explicit. Use this for config files, templates, test fixtures. For raw bytes, Files.readAllBytes does the same without decoding.

Large files shouldn't be loaded all at once. The right tool there is Files.newBufferedReader and line-by-line processing, or channels, which the next part covers.

Exercise

Write a method with this signature:

long countLines(Path path, Charset charset) throws IOException

Enter fullscreen mode Exit fullscreen mode

It should count the number of newline-terminated lines in the file. What happens if you pass StandardCharsets.ISO_8859_1 to a UTF-8 file that contains only ASCII characters? What about a file that contains 'á' (U+00E1)?

For the first case, every ASCII character has the same byte value in both UTF-8 and ISO-8859-1. The newline byte 0x0A decodes identically in both charsets, so the line count is correct. For the second case, 'á' in UTF-8 is the two-byte sequence 0xC3 0xA1. ISO-8859-1 decodes each byte separately, so 0xC3 becomes 'Ã' and 0xA1 becomes '¡'. The line count is still correct — neither byte is a newline — but every 'á' becomes two wrong characters.

The bytes didn't change. Only the interpretation did.

Top comments (0)