Language Features
File Handling
Complete lesson for File Handling using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — File Handling
Section: Language Features. java.io and java.nio.file: Path, Files, readers/writers, and try-with-resources.
Two APIs: java.io.File and NIO.2
java.io.Fileis the older abstract pathname. Preferjava.nio.file.Path+Files(Java 7+) for new code.Pathis obtained fromPath.of("notes.txt")(Java 11) orPaths.get(...).- Always specify a charset (
UTF_8) when reading/writing text.
| Task | Modern API | Classic API |
|---|---|---|
| Read whole file | Files.readString(path) (Java 11) | FileReader + loop |
| Write whole file | Files.writeString(path, text) | FileWriter |
| Line by line | Files.lines or BufferedReader | BufferedReader.readLine |
| Check exists | Files.exists(path) | file.exists() |
| List directory | Files.list / walk | file.listFiles() |
try-with-resources
- Any
AutoCloseable(Reader,Writer,InputStream,Scanneron a file) should be opened intry ( ... ).close()runs even if you throw. - Do not swallow
IOException. Declarethrows IOExceptiononmainin small programs or catch and rethrow as unchecked.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileBasics {
public static void main(String[] args) throws IOException {
Path path = Path.of("hello.txt");
Files.writeString(path, "Hello, file!\n", StandardCharsets.UTF_8);
String text = Files.readString(path, StandardCharsets.UTF_8);
System.out.print(text);
}
} Buffered line I/O
BufferedReader/BufferedWriterwrap character streams for efficient line reads and writes.Files.newBufferedReader(path, UTF_8)is the NIO factory.
Advanced — File Handling
Exceptions, atomic writes, and binary
- File APIs throw **checked**
IOException(andNoSuchFileException,AccessDeniedException). You must handle or declare them. Files.readAllBytes/writefor binary. Do not load multi-gigabyte files withreadString.- For interviews, mention try-with-resources vs
finally { if (br != null) br.close(); }. - Closing
ScanneronSystem.incloses stdin — fine at the end ofmain, bad in libraries.
Tricky Interview Points
Q1) File vs Path?
Answer File is the legacy pathname object. Path (NIO.2) plus Files is the modern API: better exceptions, symbolic links, and utilities.
Q2) What is try-with-resources?
Answer A try that declares AutoCloseable resources. Java calls close() automatically, including when an exception is thrown.
Q3) Why UTF-8 explicitly?
Answer Default charset used to be platform-dependent. Always pass StandardCharsets.UTF_8 so files are portable.
Q4) Is IOException checked?
Answer Yes. Callers must catch it or declare throws IOException.
Q5) How do you read a file line by line without loading it all?
Answer BufferedReader.readLine in a loop, or Files.lines (close the Stream).
Q6) What does Files.writeString do if the file exists?
Answer By default it truncates and overwrites. You can pass StandardOpenOption.APPEND to add to the end.
Simple Programs
Write, read, and count lines
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class LineCount {
public static void main(String[] args) throws IOException {
Path path = Path.of("sample.txt");
Files.writeString(path, "alpha\nbeta\ngamma\n", StandardCharsets.UTF_8);
int lines = 0;
try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
while (br.readLine() != null) {
lines++;
}
}
System.out.println("lines = " + lines);
}
} Problem Solving Tricks
- Use
Path.ofandFilesfor new code; keepFilewhen an old API demands it (File↔path.toFile()). - try-with-resources can declare several resources, separated by
;. - Never ignore
IOExceptionwith an empty catch. - Build paths with
Path.of("dir", "file.txt")instead of string concatenation and\\.
Practice Programs List
- Write three lines to a file and read them back with
Files.readAllLines. - Copy a text file using
BufferedReaderandBufferedWriter. - Append a timestamp line with
StandardOpenOption.APPEND(create the file if missing). - List all
.javafiles in a folder withFiles.listand anendsWithfilter. - Handle a missing file and print a friendly message instead of a stack trace.