StandardCharsets for Common Encodings
What you'll learn: How to use Java's StandardCharsets class to specify character encodings safely and clearly without relying on string-based charset names.
In the previous lesson, you learned to specify a Charset in InputStreamReader and OutputStreamWriter constructors. You could pass the charset as a string like "UTF-8", but this has risks: typos can cause runtime exceptions, and string literals aren't checked at compile time.
Java provides the java.nio.charset.StandardCharsets class to solve this problem. It contains static constants representing the most commonly used character encodings, guaranteed to be available on every Java platform.
The Three Most Common StandardCharsets
import java.nio.charset.StandardCharsets;
// UTF-8: The universal standard for text encoding
StandardCharsets.UTF_8
// US-ASCII: Basic 7-bit ASCII characters (A-Z, 0-9, etc.)
StandardCharsets.US_ASCII
// ISO-8859-1 (Latin-1): Western European characters
StandardCharsets.ISO_8859_1
Why This Matters
Compile-time safety: If you mistype a string like "UTf-8", Java won't catch the error until runtime. Using StandardCharsets.UTF_8 ensures correctness at compile time.
Clarity: Code readers instantly know which encoding you're using without parsing a string.
No exceptions: String-based charset names can throw UnsupportedEncodingException. The standard charsets never will.
Example Usage
import java.io.*;
import java.nio.charset.StandardCharsets;
// Reading with explicit UTF-8 encoding
try (InputStreamReader reader = new InputStreamReader(
new FileInputStream("data.txt"),
StandardCharsets.UTF_8)) {
// Read text safely decoded as UTF-8
}
// Writing with explicit ISO-8859-1 encoding
try (OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("output.txt"),
StandardCharsets.ISO_8859_1)) {
writer.write("Hello, World!");
}
Key Takeaway: Always use StandardCharsets constants (UTF_8, US_ASCII, ISO_8859_1) instead of string literals for compile-time-safe, clear encoding specifications in your I/O operations.