How to write to a file in Java

[CG]BOUGA
1,094 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
1
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// {...}
Path file = Paths.get("file.txt");
// Method 1: small files: write raw bytes
byte[] bytes = "1st line\n".getBytes();
Files.write(file, bytes);
// Method 2: small files: write lines
List<String> lines = Arrays.asList(
"2nd line",
"3rd line",
"4th line"
);
Files.write(file, lines, APPEND); // UTF8 by default
// Method 3: big files: write text
try (BufferedWriter writer = Files.newBufferedWriter(file, APPEND)) {
String line = "5th line";
writer.write(line, 0, line.length());
writer.newLine();
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content