File Handling in Java Complete Guide
File handling in Java lets a program create, read, write, and delete files on disk. Java provides the File class along with I/O classes like FileReader, FileWriter, and BufferedReader for these operations.
Creating a File
import java.io.File;
import java.io.IOException;
File file = new File("data.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
}
Writing to a File
import java.io.FileWriter;
import java.io.IOException;
FileWriter writer = new FileWriter("data.txt");
writer.write("Hello, Uncodemy learners!");
writer.close();
Reading from a File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Deleting a File
File file = new File("data.txt");
if (file.delete()) {
System.out.println("Deleted: " + file.getName());
}
Key Classes for File Handling
File— represents a file or directory path and provides methods to create, delete, or inspect itFileReader/FileWriter— read and write character dataBufferedReader/BufferedWriter— add buffering for more efficient reading and writingFileInputStream/FileOutputStream— read and write raw binary data
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.
Safer Code with try-with-resources
The earlier snippets call close() by hand, but if an exception happens before that line, the file stays open. A try-with-resources block closes every resource declared in its header automatically, whether the code finishes normally or fails.
import java.io.*;
import java.nio.charset.StandardCharsets;
try (BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("log.txt", true), StandardCharsets.UTF_8))) {
out.write("Job finished");
out.newLine();
} catch (IOException e) {
System.err.println("Could not write log: " + e.getMessage());
}
Two details matter here. The second argument true opens the file in append mode, so new lines are added instead of replacing the file. And the explicit UTF-8 charset avoids surprises when the program runs on machines with a different default encoding.
The Modern Way: java.nio.file
The java.nio.file package, built around Path and Files, is usually shorter and gives clearer error messages than the older java.io.File API. Methods like Files.writeString and Files.readString are available from Java 11 onwards.
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
Path path = Path.of("notes.txt");
Files.writeString(path, "first line\n"); // create or overwrite
Files.writeString(path, "second line\n", StandardOpenOption.APPEND);
List<String> lines = Files.readAllLines(path); // small files
try (Stream<String> stream = Files.lines(path)) { // large files, read lazily
stream.filter(l -> l.contains("line")).forEach(System.out::println);
}
Files.copy(path, Path.of("backup.txt"), StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(path);
Note that Files.lines returns a stream that holds the file open, so it also belongs in a try-with-resources block.
Which API to pick
| Task | Good choice |
|---|---|
| Read or write a small text file | Files.readString / Files.writeString |
| Process a large file line by line | Files.lines or BufferedReader |
| Images, PDFs or other binary data | Files.readAllBytes or buffered byte streams |
| Work in legacy code | java.io classes, with try-with-resources |
Working with Folders and File Details
File handling is not only about reading and writing text. Programs often need to create a folder tree, check whether something exists, or list the files in a directory. The Files class covers all of these in a consistent way.
Path reports = Path.of("output", "reports", "monthly");
Files.createDirectories(reports); // creates missing parent folders too
System.out.println(Files.exists(reports)); // true
System.out.println(Files.isDirectory(reports)); // true
try (Stream<Path> entries = Files.list(Path.of("output"))) {
entries.forEach(p -> System.out.println(p.getFileName()));
}
long bytes = Files.size(Path.of("backup.txt"));
Use Path.of with separate parts instead of typing slashes yourself. Java then picks the right separator for Windows, macOS or Linux, so the same code runs everywhere. Like Files.lines, the stream from Files.list must be closed.
Errors Beginners Run Into
- Relative paths behave unexpectedly. A path like
data.txtis resolved from the working directory, which differs between an IDE and the command line. Printpath.toAbsolutePath()while debugging. - Swallowing exceptions. An empty
catchblock hides problems such as missing permissions. At least log the message. - Reading huge files into memory.
readAllLinesloads everything at once; stream the file instead. - Ignoring the result of delete or createNewFile. These old methods return
falseinstead of throwing, so check the return value, or use theFilesversions that throw clear exceptions. - Forgetting to flush. Buffered writers hold data in memory until flushed or closed.
Practical checklist: use Path and Files for new code, always set a charset for text, wrap every stream in try-with-resources, and handle IOException with a useful message.