Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
49
50
51
// {
import static java.nio.file.StandardOpenOption.APPEND;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
// }
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();
}
//{
try (BufferedReader reader = Files.newBufferedReader(file)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
//}
Press desired key combination and then press ENTER.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content