-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathwriting-files.yaml
More file actions
48 lines (48 loc) · 1.37 KB
/
writing-files.yaml
File metadata and controls
48 lines (48 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
---
id: 58
slug: "writing-files"
title: "Writing files"
category: "io"
difficulty: "beginner"
jdkVersion: "11"
oldLabel: "Java 8"
modernLabel: "Java 11+"
oldApproach: "FileWriter + BufferedWriter"
modernApproach: "Files.writeString()"
oldCode: |-
try (FileWriter fw =
new FileWriter("out.txt");
BufferedWriter bw =
new BufferedWriter(fw)) {
bw.write(content);
}
modernCode: |-
Files.writeString(
Path.of("out.txt"),
content
);
summary: "Write a String to a file with one line."
explanation: "Files.writeString() writes content to a file with UTF-8 encoding by\
\ default. Options can be passed for appending, creating, etc."
whyModernWins:
- icon: "📏"
title: "One line"
desc: "No writer wrapping or try-with-resources needed."
- icon: "🛡️"
title: "Safe defaults"
desc: "UTF-8 encoding, proper file handle cleanup."
- icon: "🔧"
title: "Options"
desc: "Pass OpenOption flags for append, create, etc."
support:
state: "available"
description: "Widely available since JDK 11 (Sept 2018)"
prev: "io/reading-files"
next: "io/inputstream-transferto"
related:
- "io/reading-files"
- "io/http-client"
- "io/path-of"
docs:
- title: "Files.writeString()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Files.html#writeString(java.nio.file.Path,java.lang.CharSequence,java.nio.file.OpenOption...)"