Sub topic 4
Character encodings: always know your charset
This chapter assumes Java 11 or later, basic Java syntax, and familiarity with Path, Files, checked exceptions, and try/catch. It focuses on choosing a character encoding when Java converts between text and file bytes.
Text is stored as bytes
A text file stores bytes. A Java String stores characters. A character encoding, also called a charset, defines how characters become bytes and how bytes become characters.
For example, UTF-8 represents the character é with more than one byte. Reading those bytes with the wrong charset can produce incorrect text or a decoding error.
UTF-8 is a common choice because it can represent characters from many writing systems and works well across operating systems.
Specify the charset explicitly
Java provides named charsets through StandardCharsets. Passing StandardCharsets.UTF_8 documents the file format and avoids depending on the computer's default charset.
| Operation | Explicit API |
|---|---|
| Read all text | `Files.readString(path, charset)` |
| Write all text | `Files.writeString(path, text, charset)` |
| Open a reader | `Files.newBufferedReader(path, charset)` |
| Open a writer | `Files.newBufferedWriter(path, charset)` |
The following program writes and reads the same UTF-8 file:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class CharsetDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("message.txt");
String message = "Café — привет — こんにちは";
Files.writeString(file, message, StandardCharsets.UTF_8);
String loaded = Files.readString(file, StandardCharsets.UTF_8);
System.out.println(loaded);
}
}The three-argument writeString method creates the file if needed and replaces its existing contents by default. The matching readString call decodes the bytes as UTF-8.
Avoid the platform default
Some overloads do not take a charset. They may use a default selected by the operating system or Java runtime. That default can differ between a developer's computer, a test server, and a production system.
A file written with the default charset might be unreadable when another system uses a different default. Use an explicit charset whenever the file format matters.
A charset is part of a file's contract. If an external system specifies Windows-1252, ISO-8859-1, or another encoding, use that specified charset instead of assuming UTF-8.
Use the same charset for buffered I/O
For large files, use a buffered reader or writer and pass the charset explicitly. try-with-resources closes the file automatically.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadUtf8Lines {
public static void main(String[] args) throws IOException {
Path file = Path.of("message.txt");
try (BufferedReader reader =
Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}If the bytes cannot be decoded using the selected charset, the operation can throw an IOException, often with a more specific decoding exception as its cause. Handle that failure when the file comes from an untrusted or unreliable source.
Exercise
Why should a program pass StandardCharsets.UTF_8 to both writeString and readString?
Show answer
The same explicit charset makes the conversion from characters to bytes and back predictable across different operating systems.