8.1 Text File I/O and Paths
Files store data persistently. Variables in memory disappear when a program ends, but data written to a file can remain. File I/O means input from files and output to files.
Java has several file APIs. For modern beginner code, the most useful starting point is java.nio.file.Path plus java.nio.file.Files.
Path and Files
Path represents where a file or directory is. Files contains many static methods that read, write, copy, move, delete, and inspect paths.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadWholeFileDemo {
public static void main(String[] args) throws IOException {
Path path = Path.of("notes.txt");
String content = Files.readString(path, StandardCharsets.UTF_8);
System.out.println(content);
}
}Path.of("notes.txt") does not read the file. It only builds a path object. Files.readString(...) is the operation that opens the file, reads bytes, decodes them as UTF-8 text, closes the file, and returns one String.
java.io.File class. You will still see it in older code, but Path and Files are usually clearer for new code.Reading Small Text Files
For small files, Files.readString() is convenient because it gives you the whole file at once.
Path path = Path.of("quote.txt");
String text = Files.readString(path, StandardCharsets.UTF_8);
System.out.println(text);If you want all lines as a list, use Files.readAllLines().
import java.util.List;
Path path = Path.of("quote.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (int i = 0; i < lines.size(); i++) {
System.out.println((i + 1) + ": " + lines.get(i));
}Use these methods when the file is comfortably small. If the file may be large, prefer line-by-line reading, which Chapter 8.2 covers.
IOException
File operations can fail for reasons outside your program: the file might be missing, the path might point to a directory, permissions might block access, or the disk might be unavailable. Many Java file methods throw IOException, a checked exception.
A checked exception must be handled or declared. In small demo programs you may write throws IOException on main:
public static void main(String[] args) throws IOException {
String text = Files.readString(Path.of("notes.txt"), StandardCharsets.UTF_8);
System.out.println(text);
}In user-facing programs, you often catch the exception and print a helpful message:
try {
String text = Files.readString(Path.of("notes.txt"), StandardCharsets.UTF_8);
System.out.println(text);
} catch (IOException error) {
System.out.println("Could not read notes.txt: " + error.getMessage());
}The important idea is not "always catch" or "always throws." The important idea is to decide where the program can respond usefully.