Files and the NIO.2 API
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Two file APIs
Java has an old file API, java.io.File, and a newer one, NIO.2, in the package java.nio.file. The newer one is better in almost every way, with clearer error messages, symbolic link support and many convenient methods. Use it for new code. The two central types are Path, which represents a location, and Files, a class full of static methods that operate on paths.
Paths
A Path does not need to exist. It is only a description of a location. You create one with Path.of("folder", "file.txt"), and Java uses the separator of the current operating system. You can combine paths with resolve, as in dir.resolve("notes.txt"). Never glue paths together with string concatenation and slashes.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
try {
Path dir = Files.createTempDirectory("java-files-demo");
System.out.println("Working in " + dir);
// 1. Write and read a whole text file (UTF-8 by default)
Path notes = dir.resolve("notes.txt");
Files.writeString(notes, "First line\nSecond line\n");
Files.writeString(notes, "Third line\n", StandardOpenOption.APPEND);
String all = Files.readString(notes);
System.out.print(all);
// 2. Read lines into a list
List<String> lines = Files.readAllLines(notes);
System.out.println("Line count: " + lines.size());
// 3. Read a large file lazily; close the stream
try (Stream<String> stream = Files.lines(notes)) {
long longLines = stream.filter(line -> line.length() > 10).count();
System.out.println("Lines longer than 10 characters: " + longLines);
}
// 4. Write line by line with a BufferedWriter
Path report = dir.resolve("report.csv");
try (BufferedWriter writer = Files.newBufferedWriter(report, StandardCharsets.UTF_8)) {
writer.write("name,score");
writer.newLine();
writer.write("Ayesha,91");
writer.newLine();
writer.write("Bilal,78");
writer.newLine();
}
// 5. Parse the CSV
int total = 0;
for (String line : Files.readAllLines(report).subList(1, 3)) {
String[] parts = line.split(",");
total += Integer.parseInt(parts[1]);
}
System.out.println("Total score: " + total);
// 6. Copy, check, list, delete
Path backup = dir.resolve("backup.csv");
Files.copy(report, backup, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Backup exists: " + Files.exists(backup) + ", size " + Files.size(backup) + " bytes");
try (Stream<Path> entries = Files.list(dir)) {
entries.map(p -> p.getFileName().toString()).sorted().forEach(System.out::println);
}
// 7. A missing file gives a checked exception
try {
Files.readString(dir.resolve("missing.txt"));
} catch (java.nio.file.NoSuchFileException e) {
System.out.println("No such file: " + e.getFile().endsWith("missing.txt"));
}
// 8. Clean up
try (Stream<Path> entries = Files.list(dir)) {
for (Path p : entries.toList()) {
Files.delete(p);
}
}
Files.delete(dir);
System.out.println("Cleaned up: " + !Files.exists(dir));
} catch (IOException e) {
System.err.println("File operation failed: " + e);
}
}
}
Walking through it
Files.createTempDirectory gives us a safe place to experiment, so the example does not touch your own files. The whole program sits inside one try, because nearly every Files method declares IOException, which is a checked exception.
writeString and readString, added in Java 11, are the simplest way to handle small files. They use UTF-8 unless you pass another charset. Always know your encoding. Old tutorials rely on the platform default, which differs between machines and causes unreadable text. By default writeString creates or overwrites the file. Pass StandardOpenOption.APPEND to add to the end instead.
readAllLines loads the whole file into memory as a list. It is fine for small and medium files. For a file with millions of lines, use Files.lines, which returns a lazy Stream<String>. The stream holds the file open, so it must be closed. The try-with-resources block does that. Forgetting it leaks a file handle. The same applies to Files.list and Files.walk.
For writing many lines, Files.newBufferedWriter returns a BufferedWriter that collects output and writes it in efficient chunks. Closing it flushes whatever is left. If you forget to close a writer, the last part of the data may never reach the disk.
The CSV part is deliberately simple. The first line is a header, so we skip it with subList(1, 3). Real CSV files can contain quoted commas and line breaks, and for those you should use a library instead of split.
Files.copy refuses to overwrite by default and throws FileAlreadyExistsException, so we pass REPLACE_EXISTING. Files.exists and Files.size answer simple questions about a path.
The missing-file case shows that NIO throws specific subclasses of IOException, here NoSuchFileException. That is much more helpful than the old File API, where many methods just returned false. At the end we delete the files and then the now-empty directory, because Files.delete refuses to remove a directory with contents.
Useful methods to remember
Files.createDirectories(path)creates a directory and any missing parents.Files.walk(path)streams a whole directory tree.Files.move(source, target)moves or renames.Files.isDirectory(path)andFiles.isRegularFile(path)tell you what a path is.Files.deleteIfExists(path)does not complain when the file is already gone.
Common mistakes
- Not closing streams from
Files.lines,listandwalk. - Assuming relative paths point where the source file is. They are relative to the working directory of the process.
- Reading a huge file with
readAllLines. You may run out of memory. - Relying on the default charset. State UTF-8.
- Building paths with
"/"or"\\"in strings.
Try it yourself
- Write a program that appends a timestamped line to
journal.txtevery time it runs, and prints the whole journal. - Count the words in a text file using
Files.lines. - Walk a directory with
Files.walkand print the ten largest files.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
try {
Path dir = Files.createTempDirectory("java-files-demo");
System.out.println("Working in " + dir);
// 1. Write and read a whole text file (UTF-8 by default)
Path notes = dir.resolve("notes.txt");
Files.writeString(notes, "First line\nSecond line\n");
Files.writeString(notes, "Third line\n", StandardOpenOption.APPEND);
String all = Files.readString(notes);
System.out.print(all);
// 2. Read lines into a list
List<String> lines = Files.readAllLines(notes);
System.out.println("Line count: " + lines.size());
// 3. Read a large file lazily; close the stream
try (Stream<String> stream = Files.lines(notes)) {
long longLines = stream.filter(line -> line.length() > 10).count();
System.out.println("Lines longer than 10 characters: " + longLines);
}
// 4. Write line by line with a BufferedWriter
Path report = dir.resolve("report.csv");
try (BufferedWriter writer = Files.newBufferedWriter(report, StandardCharsets.UTF_8)) {
writer.write("name,score");
writer.newLine();
writer.write("Ayesha,91");
writer.newLine();
writer.write("Bilal,78");
writer.newLine();
}
// 5. Parse the CSV
int total = 0;
for (String line : Files.readAllLines(report).subList(1, 3)) {
String[] parts = line.split(",");
total += Integer.parseInt(parts[1]);
}
System.out.println("Total score: " + total);
// 6. Copy, check, list, delete
Path backup = dir.resolve("backup.csv");
Files.copy(report, backup, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Backup exists: " + Files.exists(backup) + ", size " + Files.size(backup) + " bytes");
try (Stream<Path> entries = Files.list(dir)) {
entries.map(p -> p.getFileName().toString()).sorted().forEach(System.out::println);
}
// 7. A missing file gives a checked exception
try {
Files.readString(dir.resolve("missing.txt"));
} catch (java.nio.file.NoSuchFileException e) {
System.out.println("No such file: " + e.getFile().endsWith("missing.txt"));
}
// 8. Clean up
try (Stream<Path> entries = Files.list(dir)) {
for (Path p : entries.toList()) {
Files.delete(p);
}
}
Files.delete(dir);
System.out.println("Cleaned up: " + !Files.exists(dir));
} catch (IOException e) {
System.err.println("File operation failed: " + e);
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account