Character Encoding with Charset Parameters
What you'll learn: How to explicitly specify character encodings when reading and writing files to ensure your text is interpreted correctly across different systems and languages.
When you read or write text files in Java, the bytes on disk must be converted to characters (and vice versa). This conversion depends on a character encoding — a rulebook that maps bytes to characters. If you use the wrong encoding, you'll see garbled text (like "é" instead of "é") or even data loss.
Why Explicit Encoding Matters
Without specifying an encoding, Java uses your system's default charset, which varies by operating system and locale. A file written on Windows might use Windows-1252, while Linux often uses UTF-8. If you open that Windows file on Linux without specifying the encoding, special characters will break.
Specifying Charset Parameters
Most NIO.2 methods accept a Charset parameter to make encoding explicit:
Path path = Paths.get("data.txt");
// Reading with explicit UTF-8 encoding
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Writing with explicit UTF-8 encoding
Files.writeString(path, "Café ☕", StandardCharsets.UTF_8);
// Buffered readers/writers with encoding
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.ISO_8859_1);
Common Encodings
- UTF-8: Universal, space-efficient for English, supports all Unicode characters — use this by default
- ISO-8859-1 (Latin-1): Western European languages, single-byte encoding
- US-ASCII: Basic English characters only
Key Takeaway: Always explicitly specify a Charset (preferably StandardCharsets.UTF_8) when reading or writing text files to ensure consistent, correct interpretation across different systems and avoid platform-dependent bugs.