Programs often need to save data so it survives after they stop: settings, logs, reports or exported records. Java’s modern java.nio.file API, built around the Path and Files classes, makes reading and writing text files short and safe. This lesson shows the one-line helpers for small files, buffered reading and writing for large ones, try-with-resources, and how to handle missing files.
In this lesson you will learn
- Creating paths with
Path.of - Writing and appending with
Files.writeString - Reading lines with
Files.readAllLines - Buffered reading and writing for large files
- try-with-resources and I/O exceptions
Reading and Writing Small Files
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Path file = Path.of("marks.txt");
Files.writeString(file, "Nadia,78\nRafi,64\n"); // create or overwrite
Files.writeString(file, "Mitu,91\n", java.nio.file.StandardOpenOption.APPEND);
List<String> lines = Files.readAllLines(file);
int total = 0;
for (String line : lines) {
String[] parts = line.split(",");
System.out.println(parts[0] + " scored " + parts[1]);
total += Integer.parseInt(parts[1]);
}
System.out.println("Lines: " + lines.size() + ", total: " + total);
System.out.println("Exists: " + Files.exists(file) + ", bytes: " + Files.size(file));
Files.delete(file);
System.out.println("Exists after delete: " + Files.exists(file));
}
}
Output
Nadia scored 78
Rafi scored 64
Mitu scored 91
Lines: 3, total: 233
Exists: true, bytes: 25
Exists after delete: false
Path.of("marks.txt")refers to a file in the current working directory. UsePath.of("data", "marks.txt")to build paths that work on Windows, Linux and macOS.Files.writeStringcreates the file or replaces its contents. PassingStandardOpenOption.APPENDadds to the end instead.Files.readAllLinesreturns aList<String>, one entry per line, ready for parsing.Files.readStringreturns the whole file as one string.Files.exists,Files.sizeandFiles.deleteinspect and manage files.- File methods throw the checked exception
IOException, so the method declaresthrows IOException. See Exception Handling. - Text is read and written as UTF-8 by default, so Bangla and other non-English text works correctly.
Buffered I/O and try-with-resources
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path log = Path.of("app.log");
// try-with-resources closes the writer automatically
try (BufferedWriter w = Files.newBufferedWriter(log)) {
for (int i = 1; i <= 3; i++) {
w.write("event " + i);
w.newLine();
}
} catch (IOException e) {
System.out.println("Write failed: " + e.getMessage());
}
try (BufferedReader r = Files.newBufferedReader(log)) {
String line;
while ((line = r.readLine()) != null) { // null means end of file
System.out.println("read: " + line);
}
} catch (IOException e) {
System.out.println("Read failed: " + e.getMessage());
}
try {
Files.readString(Path.of("missing.txt"));
} catch (NoSuchFileException e) {
System.out.println("No such file: " + e.getMessage());
} catch (IOException e) {
System.out.println("Other I/O error");
}
try { Files.deleteIfExists(log); } catch (IOException e) { }
}
}
Output
read: event 1
read: event 2
read: event 3
No such file: missing.txt
readAllLinesloads the whole file into memory. For large files, aBufferedReaderreads one line at a time;readLine()returnsnullat the end of the file.BufferedWritercollects output in memory and writes it in chunks, which is much faster than writing character by character.- try-with-resources,
try (BufferedWriter w = ...) { }, closes the file automatically when the block ends, even if an exception is thrown. Unclosed files can lose data or stay locked. NoSuchFileExceptionis a subclass ofIOException, so it is caught first to give a specific message.
Handy Files Methods
| Method | Purpose |
|---|---|
Files.readString(p) / writeString(p, s) | Whole file as one string |
Files.readAllLines(p) / write(p, lines) | File as a list of lines |
Files.lines(p) | A lazy stream of lines (close it with try-with-resources) |
Files.exists(p), Files.size(p) | Check a file |
Files.createDirectories(p) | Create folders, including parents |
Files.copy(a, b), Files.move(a, b) | Copy or move |
Files.delete(p), Files.deleteIfExists(p) | Delete |
Older code uses java.io.File, FileReader and FileWriter. They still work, but Path and Files give clearer error messages and better defaults.
Common Mistakes
- Not closing streams; always use try-with-resources.
- Hard-coding Windows paths such as
"C:\\data\\x.txt"; build paths withPath.of. - Overwriting by accident:
writeStringreplaces the file unless you passAPPEND. - Reading huge files with
readAllLines, which can run out of memory.
Practice Exercises
Exercise 1. Count the lines in a file that contain the word “ERROR”.
Show answer
try (Stream<String> lines = Files.lines(Path.of("app.log"))) {
long errors = lines.filter(l -> l.contains("ERROR")).count();
System.out.println(errors);
}
Exercise 2. Write a list of names to names.txt, one per line.
Show answer
List<String> names = List.of("Nadia", "Rafi", "Mitu");
Files.write(Path.of("names.txt"), names);
Frequently Asked Questions
Where is a relative path like “marks.txt” saved?
In the program’s working directory, usually the folder you ran java from or the project folder in an IDE. Print Path.of("").toAbsolutePath() to check.
How do I read a CSV file properly?
For simple files, split each line on commas as shown above. For real CSV data with quoted fields containing commas, use a library such as OpenCSV or Apache Commons CSV.
Summary
- Use
PathandFilesfor modern file handling. writeString/readAllLinessuit small files; buffered readers suit large ones.- try-with-resources closes files automatically.
- Handle
IOException, andNoSuchFileExceptionfor missing files.
Next: Java Multithreading.
