8. Input/Output (IO)

Modern Java code should usually start with Path and Files from java.nio.file. Older File and stream classes are still useful, but Path and Files cover many common tasks with less ceremony.

8.1. Path and Files

1import java.nio.file.Files;
2import java.nio.file.Path;
3import java.util.List;
1public static void main(String[] args) throws Exception {
2  Path path = Path.of("test.txt");
3  List<String> names = List.of("John", "Jack", "Jane", "Joyce");
4
5  Files.write(path, names);
6  String text = Files.readString(path);
7
8  System.out.println(text);

8.2. Writing to a file

The next example uses older writer classes. This style is still common in existing code and remains useful when you need detailed control over buffering or streaming.

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}

8.3. Reading from a file

8.3.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}

8.3.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}

8.3.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);