16. Input/Output (IO)

16.1. Writing to a file

1import java.io.BufferedWriter;
2import java.io.File;
3import java.io.FileWriter;
4import java.util.Arrays;
5import java.util.List;
1List<String> names = Arrays.asList("John", "Jack", "Jane", "Joyce");
2
3try (var writer = new BufferedWriter(new FileWriter(new File("test.txt")))) {
4  for (var name : names) {
5    writer.write(name);
6    writer.write('\n');
7  }
8}

16.2. Reading from a file

16.2.1. Reading one line at a time

1import java.io.BufferedReader;
2import java.io.File;
3import java.io.FileReader;
1try (var reader = new BufferedReader(new FileReader(new File("test.txt")))) {
2  String line = null;
3  while ((line = reader.readLine()) != null) {
4    System.out.println(line);
5  }
6}

16.2.2. Reading all lines

1import java.nio.file.Files;
2import java.nio.file.Paths;
1for (var line : Files.readAllLines(Paths.get("test.txt"))) {
2  System.out.println(line);
3}

16.2.3. Reading whole file

1import java.nio.file.Files;
2import java.nio.file.Paths;
1String text = new String(
2    Files.readAllBytes(
3        Paths.get("test.txt")));
4
5System.out.println(text);