Skip to content

Commit 2d58cf5

Browse files
authored
Merge pull request #214 from javaevolved/copilot/explicit-charset-file-io
Add pattern: default-charset file I/O to explicit StandardCharsets
2 parents b9a084d + 9dc5910 commit 2d58cf5

19 files changed

Lines changed: 309 additions & 2 deletions
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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"

content/io/inputstream-transferto.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ whyModernWins:
3333
support:
3434
state: "available"
3535
description: "Widely available since JDK 9 (Sept 2017)"
36-
prev: "io/writing-files"
36+
prev: "io/explicit-charset-file-io"
3737
next: "io/path-of"
3838
related:
3939
- "io/writing-files"

content/io/writing-files.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ support:
3838
state: "available"
3939
description: "Widely available since JDK 11 (Sept 2018)"
4040
prev: "io/reading-files"
41-
next: "io/inputstream-transferto"
41+
next: "io/explicit-charset-file-io"
4242
related:
4343
- "io/reading-files"
4444
- "io/http-client"
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
///usr/bin/env jbang "$0" "$@" ; exit $?
2+
//JAVA 25+
3+
import java.io.BufferedReader;
4+
import java.nio.charset.StandardCharsets;
5+
import java.nio.file.Files;
6+
import java.nio.file.Path;
7+
8+
/// Proof: explicit-charset-file-io
9+
/// Source: content/io/explicit-charset-file-io.yaml
10+
void main() throws Exception {
11+
var path = Path.of(System.getProperty("java.io.tmpdir"), "proof-charset.txt");
12+
Files.writeString(path, "content", StandardCharsets.UTF_8);
13+
14+
try (BufferedReader reader = Files.newBufferedReader(
15+
path, StandardCharsets.UTF_8)) {
16+
readAll(reader);
17+
}
18+
}
19+
20+
String readAll(BufferedReader reader) throws Exception {
21+
var sb = new StringBuilder();
22+
String line;
23+
while ((line = reader.readLine()) != null) {
24+
sb.append(line);
25+
}
26+
return sb.toString();
27+
}

social/queue.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,4 @@ security/security-manager-migration
129129
tooling/runtime-exec-to-process-builder
130130
language/raw-collections-to-generics
131131
concurrency/thread-stop-to-cooperative-cancellation
132+
io/explicit-charset-file-io

social/tweets.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,4 +1307,14 @@ concurrency/thread-stop-to-cooperative-cancellation: |-
13071307
13081308
🔗 https://javaevolved.github.io/concurrency/thread-stop-to-cooperative-cancellation.html
13091309
1310+
#Java #JavaEvolved
1311+
io/explicit-charset-file-io: |-
1312+
☕ Default-charset file I/O to explicit StandardCharsets
1313+
1314+
Use Files readers and writers with StandardCharsets constants instead of…
1315+
1316+
Platform-default charset → Explicit standard charset (JDK 7+)
1317+
1318+
🔗 https://javaevolved.github.io/io/explicit-charset-file-io.html
1319+
13101320
#Java #JavaEvolved
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
title: "تحويل إدخال/إخراج الملفات بترميز افتراضي إلى StandardCharsets صريح"
2+
oldApproach: "الترميز الافتراضي للمنصة"
3+
modernApproach: "ترميز قياسي صريح"
4+
summary: "استخدم قارئات وكاتبات Files مع ثوابت StandardCharsets بدلاً من الاعتماد على سلوك الترميز الافتراضي للمنصة والبحث عن اسم الترميز."
5+
explanation: "تجعل بواني Reader وWriter التي تعتمد على الترميز الافتراضي سلوك الملف يعتمد على بيئة التشغيل. تقبل Files.newBufferedReader() وnewBufferedWriter() ترميزاً صريحاً، بينما توفر StandardCharsets ثوابت مضمونة مثل UTF_8 دون البحث عن سلسلة نصية أو استثناء UnsupportedCharsetException."
6+
whyModernWins:
7+
- icon: "🌍"
8+
title: "نتائج قابلة للنقل"
9+
desc: "تُفكّ نفس البايتات بنفس الطريقة على أي جهاز."
10+
- icon: "🔒"
11+
title: "ثابت معرّف مسبقًا"
12+
desc: "لا يمكن أن يحتوي StandardCharsets.UTF_8 على اسم ترميز مكتوب خطأ."
13+
- icon: "🧩"
14+
title: "واجهة ملفات حديثة"
15+
desc: "يُعبَّر عن Path والتخزين المؤقت والترميز في عملية واحدة."
16+
support:
17+
description: "متاح على نطاق واسع منذ JDK 7 (يوليو 2011)"
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
title: "ডিফল্ট চারসেট ফাইল I/O থেকে স্পষ্ট StandardCharsets এ"
2+
oldApproach: "প্ল্যাটফর্ম ডিফল্ট চারসেট"
3+
modernApproach: "স্পষ্ট স্ট্যান্ডার্ড চারসেট"
4+
summary: "প্ল্যাটফর্মের ডিফল্ট চারসেট আচরণ এবং চারসেট-নাম লুকআপের পরিবর্তে StandardCharsets কনস্ট্যান্ট সহ Files রিডার এবং রাইটার ব্যবহার করুন।"
5+
explanation: "Reader এবং Writer কনস্ট্রাক্টর যা ডিফল্ট চারসেটের উপর নির্ভর করে তা ফাইলের আচরণকে রানটাইম এনভায়রনমেন্টের উপর নির্ভরশীল করে তোলে। Files.newBufferedReader() এবং newBufferedWriter() একটি স্পষ্ট Charset গ্রহণ করে, যেখানে StandardCharsets স্ট্রিং লুকআপ বা UnsupportedCharsetException ছাড়াই UTF_8 এর মতো নিশ্চিত কনস্ট্যান্ট প্রদান করে।"
6+
whyModernWins:
7+
- icon: "🌍"
8+
title: "পোর্টেবল ফলাফল"
9+
desc: "একই বাইট প্রতিটি মেশিনে একইভাবে ডিকোড হয়।"
10+
- icon: "🔒"
11+
title: "পূর্বনির্ধারিত কনস্ট্যান্ট"
12+
desc: "StandardCharsets.UTF_8 এ ভুল বানানযুক্ত চারসেট নাম থাকতে পারে না।"
13+
- icon: "🧩"
14+
title: "আধুনিক ফাইল API"
15+
desc: "Path, বাফারিং এবং এনকোডিং একটি অপারেশনে প্রকাশ করা হয়।"
16+
support:
17+
description: "JDK 7 (জুলাই 2011) থেকে ব্যাপকভাবে উপলব্ধ"
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
title: "Standard-Charset-Datei-I/O zu explizitem StandardCharsets"
2+
oldApproach: "Plattformabhängiger Standard-Zeichensatz"
3+
modernApproach: "Expliziter Standard-Zeichensatz"
4+
summary: "Verwenden Sie Files-Reader und -Writer mit StandardCharsets-Konstanten statt sich auf das plattformabhängige Standard-Charset-Verhalten und die Zeichensatznamens-Suche zu verlassen."
5+
explanation: "Reader- und Writer-Konstruktoren, die sich auf den Standard-Zeichensatz verlassen, machen das Dateiverhalten von der Laufzeitumgebung abhängig. Files.newBufferedReader() und newBufferedWriter() akzeptieren ein explizites Charset, während StandardCharsets garantierte Konstanten wie UTF_8 ohne String-Suche oder UnsupportedCharsetException bereitstellt."
6+
whyModernWins:
7+
- icon: "🌍"
8+
title: "Portable Ergebnisse"
9+
desc: "Dieselben Bytes werden auf jeder Maschine identisch dekodiert."
10+
- icon: "🔒"
11+
title: "Vordefinierte Konstante"
12+
desc: "StandardCharsets.UTF_8 kann keinen falsch geschriebenen Zeichensatznamen enthalten."
13+
- icon: "🧩"
14+
title: "Moderne Datei-API"
15+
desc: "Path, Pufferung und Kodierung werden in einer Operation ausgedrückt."
16+
support:
17+
description: "Seit JDK 7 allgemein verfügbar (Juli 2011)"
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
title: "E/S de archivos con charset por defecto a StandardCharsets explícito"
2+
oldApproach: "Charset por defecto de la plataforma"
3+
modernApproach: "Charset estándar explícito"
4+
summary: "Usa lectores y escritores de Files con constantes de StandardCharsets en lugar de depender del comportamiento del charset por defecto de la plataforma y la búsqueda por nombre de charset."
5+
explanation: "Los constructores de Reader y Writer que dependen del charset por defecto hacen que el comportamiento del archivo dependa del entorno de ejecución. Files.newBufferedReader() y newBufferedWriter() aceptan un Charset explícito, mientras que StandardCharsets ofrece constantes garantizadas como UTF_8 sin búsqueda por cadena ni UnsupportedCharsetException."
6+
whyModernWins:
7+
- icon: "🌍"
8+
title: "Resultados portables"
9+
desc: "Los mismos bytes se decodifican de forma idéntica en cualquier máquina."
10+
- icon: "🔒"
11+
title: "Constante predefinida"
12+
desc: "StandardCharsets.UTF_8 no puede contener un nombre de charset mal escrito."
13+
- icon: "🧩"
14+
title: "API de archivos moderna"
15+
desc: "Path, buffering y codificación se expresan en una sola operación."
16+
support:
17+
description: "Ampliamente disponible desde JDK 7 (julio de 2011)"

0 commit comments

Comments
 (0)