|
| 1 | +--- |
| 2 | +id: 100472fa-74b1-442f-b89d-3e6e8adcc1b1 |
| 3 | +slug: "explicit-charset-file-io" |
| 4 | +title: "Default-charset file I/O to explicit StandardCharsets" |
| 5 | +category: "io" |
| 6 | +difficulty: "beginner" |
| 7 | +jdkVersion: "7" |
| 8 | +oldLabel: "Platform-default charset" |
| 9 | +modernLabel: "Explicit standard charset" |
| 10 | +oldApproach: "Platform-default charset" |
| 11 | +modernApproach: "Explicit standard charset" |
| 12 | +oldCode: |- |
| 13 | + try (Reader reader = new FileReader(path.toFile())) { |
| 14 | + return readAll(reader); |
| 15 | + } |
| 16 | +modernCode: |- |
| 17 | + try (BufferedReader reader = Files.newBufferedReader( |
| 18 | + path, StandardCharsets.UTF_8)) { |
| 19 | + return readAll(reader); |
| 20 | + } |
| 21 | +summary: "Use Files readers and writers with StandardCharsets constants instead of platform-default charset behavior and charset-name lookup." |
| 22 | +explanation: "Reader and writer constructors that rely on the default charset make file behavior depend on the runtime environment. Files.newBufferedReader() and newBufferedWriter() accept an explicit Charset, while StandardCharsets provides guaranteed constants such as UTF_8 without string lookup or UnsupportedCharsetException. This combines the explicit-file-encoding and Charset.forName(\"UTF-8\") migrations into one coherent pattern." |
| 23 | +whyModernWins: |
| 24 | +- icon: "🌍" |
| 25 | + title: "Portable results" |
| 26 | + desc: "The same bytes decode identically on every machine." |
| 27 | +- icon: "🔒" |
| 28 | + title: "Predefined constant" |
| 29 | + desc: "StandardCharsets.UTF_8 cannot contain a misspelled charset name." |
| 30 | +- icon: "🧩" |
| 31 | + title: "Modern file API" |
| 32 | + desc: "Path, buffering, and encoding are expressed in one operation." |
| 33 | +support: |
| 34 | + state: "available" |
| 35 | + description: "Widely available since JDK 7 (July 2011)" |
| 36 | +prev: "io/writing-files" |
| 37 | +next: "io/inputstream-transferto" |
| 38 | +related: |
| 39 | +- "io/reading-files" |
| 40 | +- "io/writing-files" |
| 41 | +- "io/path-of" |
| 42 | +tags: |
| 43 | +- io |
| 44 | +docs: |
| 45 | +- title: "Files.newBufferedReader(Path, Charset)" |
| 46 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Files.html#newBufferedReader(java.nio.file.Path,java.nio.charset.Charset)" |
| 47 | +- title: "StandardCharsets" |
| 48 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/charset/StandardCharsets.html" |
0 commit comments