Sub topic 4
Character encodings: always know your charset
This chapter assumes you can read and write small files with Files.readString and Files.writeString. It explains what happens between a Java String and the bytes on disk, and how to stop that step from silently corrupting your data.
Text is bytes plus an agreement
A file stores bytes. A Java String holds characters. A charset (character encoding) is the table that maps one to the other. If the writer and the reader use different charsets, the text comes out wrong, and often nothing warns you.
The same character can take a different number of bytes in each charset:
| Charset | Constant | "e" | "é" | Notes |
|---|---|---|---|---|
| UTF-8 | `StandardCharsets.UTF_8` | 1 byte | 2 bytes | 1 to 4 bytes per character. The usual choice. |
| ISO-8859-1 (Latin-1) | `StandardCharsets.ISO_8859_1` | 1 byte | 1 byte | Covers 256 characters. Every byte value is valid. |
| US-ASCII | `StandardCharsets.US_ASCII` | 1 byte | not representable | 128 characters only. |
| UTF-16 | `StandardCharsets.UTF_16` | 2 bytes | 2 bytes | Writes a 2-byte byte-order mark first. |
StandardCharsets also defines UTF_16BE and UTF_16LE. These fix the byte order and write no byte-order mark. Java guarantees that all of these constants exist on every platform.
What the default is, and why you shouldn't rely on it
Java has two kinds of file API, and they treat defaults differently.
- The
java.nio.file.Filesmethods that deal with text (readString,writeString,readAllLines,lines,newBufferedReader,newBufferedWriter) use UTF-8 when you pass no charset. This holds on every Java version since they were added. - The older
java.ioclassesFileReader,FileWriter,InputStreamReaderandPrintWriter(String fileName)use the platform default charset,Charset.defaultCharset(). Before Java 18 that default came from the operating system and locale, for example windows-1252 on many Windows machines. Since Java 18 (JEP 400) it is UTF-8 unless configured otherwise.
If your code must run on Java 11 or 17, or you read files written by other systems, the default can differ between machines. Name the charset yourself. The code then does the same thing everywhere, and a reader of the code can see the choice.
Seeing the damage
The next program writes a word with an accented letter, then reads it back with the wrong charset. It also does the reverse, writing Latin-1 and reading it as UTF-8. The escape \u00e9 is the character é, which keeps the source file free of encoding problems.
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class CharsetDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("cafe.txt");
String word = "caf\u00e9";
Files.writeString(file, word, StandardCharsets.UTF_8);
System.out.println(Arrays.toString(Files.readAllBytes(file)));
String wrong = Files.readString(file, StandardCharsets.ISO_8859_1);
System.out.println(wrong + " has " + wrong.length() + " chars");
Files.writeString(file, word, StandardCharsets.ISO_8859_1);
System.out.println("Latin-1 size: " + Files.size(file) + " bytes");
try {
Files.readString(file);
} catch (MalformedInputException e) {
System.out.println("Not valid UTF-8: " + e.getMessage());
}
}
}The output is:
[99, 97, 102, -61, -87]
café has 5 chars
Latin-1 size: 4 bytes
Not valid UTF-8: Input length = 1Each step shows a different behavior:
- In UTF-8,
éis two bytes (-61, -87as signed Java bytes). - Latin-1 maps every byte to some character, so decoding UTF-8 bytes as Latin-1 never fails. It produces mojibake (garbled text):
éinstead ofé, and the string gets longer. - The Latin-1 byte
0xE9is not valid UTF-8 on its own. UTF-8 has strict rules about which byte sequences are legal, so decoding fails.
The asymmetry matters. A UTF-8 decoder can detect wrong input, so it fails loudly. A Latin-1 decoder cannot detect anything, so it fails silently. If you guess a charset, guess in a way that errors can surface.
Strict and lenient decoding
The Files text methods and Files.newBufferedReader use a strict decoder. Invalid bytes throw MalformedInputException, and characters the charset cannot encode throw UnmappableCharacterException. Both extend CharacterCodingException, which extends IOException. Your existing catch (IOException e) already covers them, and you can catch them first for a specific message.
Files.lines is a special case. The failure happens while the stream is being consumed, and a stream operation cannot throw a checked exception. The MalformedInputException therefore arrives wrapped in an UncheckedIOException.
Sometimes you want the opposite behavior, such as scanning a log file that may contain a few corrupt bytes. Two options exist.
The first is the String constructor. It replaces invalid sequences with the replacement character U+FFFD and never throws:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LenientRead {
public static void main(String[] args) throws IOException {
byte[] raw = Files.readAllBytes(Path.of("cafe.txt"));
String text = new String(raw, StandardCharsets.UTF_8);
System.out.println(text.contains("\uFFFD"));
}
}This prints true if cafe.txt still holds the Latin-1 bytes from the previous program.
The second is a configured decoder, which suits large files that you read line by line:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LenientLines {
public static void main(String[] args) throws IOException {
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(Files.newInputStream(Path.of("cafe.txt")), decoder))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}Encoding errors on write
Writing can fail too. If you encode text with a charset that lacks a character, the strict methods throw instead of writing a ?:
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnmappableDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("price.txt");
try {
Files.writeString(file, "5 \u20AC", StandardCharsets.US_ASCII);
} catch (CharacterCodingException e) {
System.out.println("Cannot encode: " + e.getClass().getSimpleName());
}
}
}The euro sign is not in US-ASCII, so the write throws a CharacterCodingException subclass. The failure is a feature. A silent ? in a payment file is much harder to find than an exception.
Byte-order marks
A byte-order mark (BOM) is the character U+FEFF placed at the start of a file to signal its encoding. Some Windows tools add one to UTF-8 files even though UTF-8 has no byte-order ambiguity.
- Java's UTF-8 decoder does not remove it. The first string you read begins with
\uFEFF, which is invisible when printed but breaks comparisons such asline.equals("id"). - The
UTF_16charset reads a BOM to pick the byte order. When writing, it emits a big-endian BOM. UTF_16BEandUTF_16LEneither read nor write one.
If you accept files from spreadsheets or Windows editors, strip a leading BOM:
public class Bom {
static String stripBom(String text) {
return text.startsWith("\uFEFF") ? text.substring(1) : text;
}
public static void main(String[] args) {
System.out.println(stripBom("\uFEFFid,name").equals("id,name"));
}
}Choosing a charset: decision rules
- For files you create, use UTF-8, and say so in the code.
- For files you receive, ask what encoding the producer used and document it. Do not detect it by trial.
- If you must guess, try strict UTF-8 first. Valid UTF-8 text with non-ASCII characters is rarely valid by accident, so a success is strong evidence.
- Use
Charset.forName("windows-1252")for legacy Western European data. It is not one of the guaranteed constants, so handleUnsupportedCharsetException. - Never use
FileReaderorFileWriterwithout a charset argument on code that runs on Java versions before 18.
Exercise
A program on Java 17 reads data.csv with new FileReader("data.csv") on a Windows machine and shows é where the file contains é. The file was saved as UTF-8. What causes this, and how do you fix it in java.nio.file style?
Show answer
FileReader without a charset uses the platform default, which on that Windows machine is windows-1252, not UTF-8. The UTF-8 bytes 0xC3 0xA9 are decoded as two Latin-style characters, giving é. Fix it by naming the charset: Files.newBufferedReader(Path.of("data.csv"), StandardCharsets.UTF_8), or Files.readString(Path.of("data.csv"), StandardCharsets.UTF_8) for a small file.
Exercise
You write "naïve" with Files.writeString(path, text, StandardCharsets.US_ASCII). What happens, and why is that better than writing na?ve?
Show answer
The call throws a CharacterCodingException subclass (UnmappableCharacterException) because ï has no US-ASCII encoding. The exception tells you immediately that data would be lost. Writing ? would silently corrupt the file, and the problem would surface later, far from the cause.