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.
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
- 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
2 lines: Mon: learned classes Tue: learned exceptions exists: true, bytes: 45 exists after delete: false
Handling a missing file
No such file: does-not-exist.txt
More examples
Processing a CSV file and writing a report
skipping data line 4: East,oops North 1650 South 1100 rows: 5, skipped: 1 files: [sales.csv, summary.txt]
Step-by-step explanation
Files.createDirectoriescreates the folder (and any parents) if needed and returns its Path;resolvebuilds 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
oopsthrows NumberFormatException and is reported. - For the East row,
Integer.parseIntfails beforemergeis 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:
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
Prefer
readAllLines loads everything at once and can exhaust memory; a BufferedReader processes one line at a time.
Forgetting that writing truncates
Avoid
Prefer
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
\nexplicitly, 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
- 1Write a program that counts lines, words and characters in a text file.
- 2Append 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?