Skip to content

Module 8 · Exceptions and File Handling — topic 3 of 3

File Handling

Reading and writing text files with java.nio.file (Files and Path), buffered readers and writers, appending, listing and deleting files, and processing CSV data line by line.

Beginner 18 min read·Lesson 29 of 39 in Java Programming

Learning objectives

  • Read and write text files with Files and Path
  • Process large files line by line with a BufferedReader
  • Handle IOException and file-system errors correctly

Definition

File handling means creating, reading, writing and managing files. The modern API is java.nio.file: Path represents a location in the file system and the Files class provides static methods to read, write, copy, move, delete and list files.

Introduction

Programs need to remember things between runs: settings, saved games, reports, data imported from spreadsheets. Files are the simplest way to store that data. Java has two file APIs; this lesson uses the modern java.nio.file package introduced in Java 7, which is simpler and gives better error messages than the older java.io.File.

Why it matters

Every project that saves data — libraries, inventories, contact books — needs file handling.

Reading CSV and log files is a daily task in data processing and backend work.

Detailed explanation

Paths. Path p = Path.of("data", "students.csv"); builds a path in a platform-independent way. Relative paths are resolved against the current working directory. p.getFileName(), p.getParent() and p.toAbsolutePath() inspect it.

Small files in one call. Files.writeString(p, text) writes a whole string; Files.readString(p) reads it back; Files.readAllLines(p) returns a List<String>; Files.write(p, lines) writes a list of lines. All use UTF-8 by default (Java 11+ for the String methods).

Open options. By default writing creates or truncates the file. Pass StandardOpenOption.APPEND (with CREATE) to add to the end instead.

Large files. Reading everything into memory is fine for small files. For big ones, use Files.newBufferedReader(p) and readLine() in a loop, or Files.lines(p) (a Stream, which must be closed). Write with Files.newBufferedWriter(p). Wrap readers and writers in try-with-resources.

Managing files. Files.exists, Files.isDirectory, Files.size, Files.createDirectories, Files.copy, Files.move, Files.delete, Files.deleteIfExists and Files.list (directory contents).

Errors. Almost every method throws IOException (checked): NoSuchFileException when a file is missing, AccessDeniedException without permission, DirectoryNotEmptyException when deleting a non-empty folder. Catch the specific subclass when you can react differently.

Encoding. Always be explicit about text encoding for files exchanged with other systems; UTF-8 is the right default.

Syntax

Java
Path p = Path.of("notes.txt");
Files.writeString(p, "first line\n");
Files.writeString(p, "second line\n", StandardOpenOption.APPEND);
List<String> lines = Files.readAllLines(p);
try (BufferedReader in = Files.newBufferedReader(p)) {
String line;
while ((line = in.readLine()) != null) { ... }
}
Files.deleteIfExists(p);
  • readLine returns null at the end of the file.
  • Files methods throw IOException; handle or declare it.
  • Prefer Path and Files over the legacy java.io.File class.

Code examples

Write, append and read a text file

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Path file = Path.of("diary.txt");
Files.writeString(file, "Mon: learned classes\n");
Files.writeString(file, "Tue: learned exceptions\n", StandardOpenOption.APPEND);
List<String> lines = Files.readAllLines(file);
System.out.println(lines.size() + " lines:");
for (String line : lines) System.out.println(" " + line);
System.out.println("exists: " + Files.exists(file) + ", bytes: " + Files.size(file));
Files.delete(file);
System.out.println("exists after delete: " + Files.exists(file));
}
}
Output
2 lines:
  Mon: learned classes
  Tue: learned exceptions
exists: true, bytes: 45
exists after delete: false

Handling a missing file

Java
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 p = Path.of("does-not-exist.txt");
try {
System.out.println(Files.readString(p));
} catch (NoSuchFileException e) {
System.out.println("No such file: " + e.getFile());
} catch (IOException e) {
System.out.println("Other I/O error: " + e.getMessage());
}
}
}
Output
No such file: does-not-exist.txt

More examples

Processing a CSV file and writing a report

Java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws IOException {
Path dir = Files.createDirectories(Path.of("reports"));
Path input = dir.resolve("sales.csv");
Files.write(input, List.of("region,amount", "North,1200", "South,800", "North,450", "East,oops", "South,300"));
Map<String, Integer> totals = new TreeMap<>();
int lineNo = 0, bad = 0;
try (BufferedReader in = Files.newBufferedReader(input)) {
String line = in.readLine(); // skip the header
while ((line = in.readLine()) != null) {
lineNo++;
String[] f = line.split(",");
try {
totals.merge(f[0], Integer.parseInt(f[1]), Integer::sum);
} catch (NumberFormatException e) {
bad++;
System.out.println("skipping data line " + lineNo + ": " + line);
}
}
}
Path output = dir.resolve("summary.txt");
try (BufferedWriter out = Files.newBufferedWriter(output)) {
for (Map.Entry<String, Integer> e : totals.entrySet()) {
out.write(String.format("%-6s %6d%n", e.getKey(), e.getValue()));
}
}
System.out.print(Files.readString(output));
System.out.println("rows: " + lineNo + ", skipped: " + bad);
try (var listing = Files.list(dir)) {
System.out.println("files: " + listing.map(p -> p.getFileName().toString()).sorted().toList());
}
Files.delete(input);
Files.delete(output);
Files.delete(dir);
}
}
Output
skipping data line 4: East,oops
North    1650
South    1100
rows: 5, skipped: 1
files: [sales.csv, summary.txt]

Step-by-step explanation

  • Files.createDirectories creates the folder (and any parents) if needed and returns its Path; resolve builds paths inside it.
  • The reader skips the header, then readLine() returns each line until it returns null at the end of the file.
  • Each row is split on commas and added to a TreeMap of totals; the bad amount oops throws NumberFormatException and is reported.
  • For the East row, Integer.parseInt fails before merge is called, so East never gets a total and doesn't appear in the report at all.
  • The writer formats each total into aligned columns; both the reader and writer are closed automatically by try-with-resources, and the files are deleted at the end so the example leaves nothing behind.

Expected output

Running “Processing a CSV file and writing a report” prints exactly:

TextOutput
skipping data line 4: East,oops
North 1650
South 1100
rows: 5, skipped: 1
files: [sales.csv, summary.txt]

Practical applications

  • Saving and loading application data and settings
  • Importing CSV exports from spreadsheets and other systems
  • Writing logs and reports
  • Batch jobs that process folders of files

Best practices

  • Use Path and Files from java.nio.file for new code.
  • Always close readers, writers and streams with try-with-resources.
  • Specify UTF-8 explicitly when exchanging files with other systems.

Common mistakes

Reading a huge file into memory

Avoid

List<String> lines = Files.readAllLines(Path.of("10gb.log"));

Prefer

try (BufferedReader in = Files.newBufferedReader(Path.of("10gb.log"))) {
for (String line; (line = in.readLine()) != null; ) process(line);
}

readAllLines loads everything at once and can exhaust memory; a BufferedReader processes one line at a time.

Forgetting that writing truncates

Avoid

Files.writeString(log, entry); // replaces the whole file

Prefer

Files.writeString(log, entry, StandardOpenOption.CREATE, StandardOpenOption.APPEND);

The default options create or truncate the file, so each call would erase the previous contents.

Important notes

  • File sizes depend on line endings: the example writes \n explicitly, so the size is the same on every OS.
  • Files.lines and Files.list return streams that hold the file open; always use them in try-with-resources.

Key takeaways

  • Path locates a file; Files reads, writes and manages it.
  • Use readAllLines/readString for small files and BufferedReader for large ones.
  • File operations throw IOException, often a specific subclass such as NoSuchFileException.

Try it yourself

  1. 1
    Write a program that counts lines, words and characters in a text file.
  2. 2
    Append a timestamped line to a log file each time the program runs.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich method reads all lines of a small text file into a List<String>?
  • BeginnerWhat does `Files.writeString(path, text)` do if the file already exists?
  • ModerateWhy should `Files.lines(path)` be used in try-with-resources?
Practise this topic