Java · Lesson 14 of 15
Files and I/O
Read and write files with java.nio and handle resources with try-with-resources.
- Intermediate
- 14 min read
- 3 objectives
Before this lessonLesson 13: Lambdas and Streams
What you will learn
- Read and write text files
- Use try-with-resources
- Work with Path
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Modern Java reads and writes files through java.nio.file: Path describes a location and Files does the work. Most methods throw IOException, which you must catch or declare.
Write and read a text file
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "first\nsecond\nthird\n");
List<String> lines = Files.readAllLines(file);
System.out.println(lines.size() + " lines");
System.out.println(lines.get(1));
Files.delete(file);
}
}Output
3 lines second
Big files: stream lines
readAllLines loads everything into memory. For large files read line by line with a BufferedReader.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader in = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}
}try-with-resources
Anything that implements AutoCloseable declared in the try (...) parentheses is closed automatically, even if an exception is thrown. It replaces a manual finally block.
Working with paths
import java.nio.file.*;
public class Main {
public static void main(String[] args) {
Path p = Path.of("data", "2025", "report.csv");
System.out.println(p);
System.out.println(p.getFileName());
System.out.println(p.getParent());
System.out.println(Files.exists(p));
}
}Output
Testing with JUnitWrite unit tests, assertions and run them with Maven or Gradle.
data/2025/report.csv report.csv data/2025 false
