File I/O
Reading and writing files is a daily task — logs, CSV imports, reports. Modern Java makes it short and safe.
On this page · 5 min · Intermediate
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 30, 2026
Related tutorials
In simple words#
Path is the address of a file; Files is the postman who reads letters from that address or delivers new ones.
- Path
- A file or folder location.
- Files
- Utility class: read, write, copy, delete.
- Files.lines
- Stream lines lazily for big files.
Learning objectives#
- Create paths
- Read and write text files
- Process large files line by line
- Handle I/O errors
Explanation#
Path.of("data", "orders.csv") builds a path portable across operating systems.
Files.readString / Files.writeString for small files; Files.readAllLines for a list of lines.
Files.lines(path) returns a stream — use try-with-resources so the file closes; good for large files.
Files.createDirectories, exists, copy, move and delete manage files. All throw IOException.
Code example: Import a CSV and write a summary#
import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;
public class CsvReport {
public static void main(String[] args) throws IOException {
Path dir = Path.of("data");
Files.createDirectories(dir);
Path csv = dir.resolve("orders.csv");
Files.writeString(csv, """
id,city,amount
1,Pune,55000
2,Delhi,1400
3,Pune,2200
""");
double puneTotal;
try (Stream<String> lines = Files.lines(csv)) {
puneTotal = lines.skip(1)
.map(line -> line.split(","))
.filter(cols -> cols[1].equals("Pune"))
.mapToDouble(cols -> Double.parseDouble(cols[2]))
.sum();
}
Files.writeString(dir.resolve("summary.txt"), "Pune total: " + puneTotal + System.lineSeparator());
System.out.println(Files.readString(dir.resolve("summary.txt")).strip());
}
}
Pune total: 57200.0
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- createDirectories makes the folder if missing.
- A text block writes the sample CSV.
- Files.lines streams rows; skip(1) drops the header.
- The summary is written and read back.
Real-world use case#
Nightly jobs import CSV price lists from suppliers and write summary reports for managers.
Common mistakes#
Leaks file handles. Always use try-with-resources.
split(",") breaks on quoted commas. Use a CSV library for real data.
Best practices#
- java.nio.file over old java.io.File
- Stream large files
- Specify charset when needed (UTF-8 default since Java 18)
- Handle IOException clearly
Remember this#
Path.of(...) + Files.*.
Small → readString; big → Files.lines.
try-with-resources for streams.
Practice exercise#
Your task: Append a line to log.txt, creating the file if needed.
Show solution
Files.writeString(Path.of("log.txt"), "Started\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Mini quiz#
Which method lazily streams lines from a large file?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.