File Handling in Java: Reading, Writing and Managing Files
Almost every real application works with files: it saves settings, reads uploaded data, writes reports and keeps logs. File handling is how a Java program creates, reads, writes and manages those files and folders.
This tutorial gives you the big picture: Java's two file APIs, the most common operations, two complete examples and the rules for safe, portable file code.
1. What Is File Handling in Java?
File handling means working with data that lives outside the running program, in the file system. A Java program can:
- create, rename, copy, move and delete files and folders;
- write text or binary data to a file, or append to it;
- read a file all at once, line by line or byte by byte;
- check information such as whether a file exists, its size and its last-modified time.
Because a file lives outside the JVM, many things can go wrong: the file may be missing, locked or unreadable. That is why almost every file method can throw IOException.
2. The Two File APIs: java.io and java.nio.file
Java offers two packages for file work. Modern code mostly uses java.nio.file for files and folders, while java.io streams remain the standard way to process data step by step.
Swipe sideways to see the whole diagram.
| Package | Key types | Best for |
|---|---|---|
java.io | File, byte streams, character streams | Processing data in a stream, working with older APIs |
java.nio.file (NIO.2) | Path, Files | Most file and folder tasks, with clearer errors and one-line helpers |
You can move between them at any time: file.toPath() turns a File into a Path, and path.toFile() does the reverse.
3. Common File Operations
| Task | Classic java.io | Modern java.nio.file |
|---|---|---|
| Refer to a file | new File("notes.txt") | Path.of("notes.txt") |
| Check that it exists | file.exists() | Files.exists(path) |
| Write text | FileWriter + BufferedWriter | Files.writeString(path, text) |
| Read all lines | BufferedReader.readLine() in a loop | Files.readAllLines(path) |
| Read raw bytes | FileInputStream | Files.readAllBytes(path) |
| Copy a file | Read and write through streams | Files.copy(source, target) |
| Delete a file | file.delete() (returns false on failure) | Files.delete(path) (throws an exception that explains why) |
4. Example: Saving a Grocery List with NIO.2
A shopping app stores a grocery list in a text file. It writes three items, appends one more, reads everything back and cleans up. A temporary folder keeps your own files safe.
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 GroceryListFile {
public static void main(String[] args) throws IOException {
Path folder = Files.createTempDirectory("groceries");
Path list = folder.resolve("list.txt");
Files.write(list, List.of("Rice", "Lentils", "Tomatoes")); // create the file and write three lines
Files.writeString(list, "Curd" + System.lineSeparator(),
StandardOpenOption.APPEND); // add one more line at the end
List<String> items = Files.readAllLines(list); // read every line back
System.out.println("File exists: " + Files.exists(list));
System.out.println("Items: " + items.size());
for (int i = 0; i < items.size(); i++) {
System.out.println((i + 1) + ". " + items.get(i));
}
Files.delete(list); // clean up
Files.delete(folder);
System.out.println("Deleted: " + Files.notExists(list));
}
}
File exists: true Items: 4 1. Rice 2. Lentils 3. Tomatoes 4. Curd Deleted: true
How the code works
Files.createTempDirectory()creates a new, empty folder, andresolve()builds the path oflist.txtinside it.Files.write()creates the file and writes each list element as a line. Text is encoded as UTF-8.Files.writeString()withStandardOpenOption.APPENDadds a line to the end instead of replacing the content.Files.readAllLines()returns every line as aList<String>, which suits small files.Files.delete()removes the file, then the now-empty folder.
5. Example: Counting Errors in a Log File with java.io
A support engineer wants to count the errors in a server log. The classic stream classes read the file one line at a time, so this also works for very large logs.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class LogErrorCounter {
public static void main(String[] args) throws IOException {
File log = File.createTempFile("server", ".log");
// Write a small log file as text (character stream)
try (BufferedWriter out = new BufferedWriter(new FileWriter(log, StandardCharsets.UTF_8))) {
out.write("10:01 INFO Server started");
out.newLine();
out.write("10:05 ERROR Disk quota exceeded");
out.newLine();
out.write("10:07 INFO Backup finished");
out.newLine();
out.write("10:12 ERROR Connection reset");
out.newLine();
}
// Read it back line by line and count the errors
int errors = 0;
try (BufferedReader in = new BufferedReader(new FileReader(log, StandardCharsets.UTF_8))) {
String line;
while ((line = in.readLine()) != null) {
if (line.contains("ERROR")) {
errors++;
System.out.println("Found: " + line);
}
}
}
System.out.println("Error lines: " + errors);
System.out.println("Deleted: " + log.delete());
}
}
Found: 10:05 ERROR Disk quota exceeded Found: 10:12 ERROR Connection reset Error lines: 2 Deleted: true
How the code works
File.createTempFile()creates an empty file with a unique name.FileWriterturns characters into bytes using the given charset, andBufferedWritercollects them so data is written in larger, faster chunks.newLine()adds the platform's line separator.BufferedReader.readLine()returns one line at a time andnullat the end of the file.- Both streams are opened in try-with-resources blocks, so they are closed automatically, even if an exception occurs.
6. Text, Bytes and Character Encoding
Files store bytes. Text is stored by encoding characters into bytes with a charset, such as UTF-8. Use byte streams (InputStream, OutputStream) for binary data like images, and character streams (Reader, Writer) for text.
Since Java 18, the default charset is UTF-8 on every operating system. Earlier versions used the platform's charset, so the same program could read text differently on Windows and Linux. Passing StandardCharsets.UTF_8 explicitly, as the log example does, keeps your code correct on every Java version.
7. Handling IOException
IOException is a checked exception, so the compiler requires you to catch it or declare it with throws. The examples declare it on main to stay short. In an application, catch it where you can respond, for example by telling the user the file is missing. NIO.2 throws specific subclasses such as NoSuchFileException and DirectoryNotEmptyException, which make the cause clear.
8. Common Mistakes and Best Practices
- Forgetting to close streams. Open files in try-with-resources so they are always closed.
- Relying on the default charset. Specify
StandardCharsets.UTF_8when your code must also run on Java 17 or earlier. - Loading huge files into memory.
readAllLines()andreadAllBytes()suit small files; stream large ones line by line. - Ignoring the result of
File.delete(). It returnsfalseinstead of explaining the failure;Files.delete()throws an exception with the reason. - Hard-coding separators. Build paths with
Path.of("data", "notes.txt")instead of joining strings with"\\"or"/".
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 and 1.1 | java.io with File and byte streams; Reader and Writer added in 1.1. |
| Java 7 | NIO.2 (Path, Files) and try-with-resources. |
| Java 8 | Files.lines(), Files.list() and BufferedReader.lines() return streams. |
| Java 11 | Files.readString(), Files.writeString() and Path.of(); charset constructors for FileReader and FileWriter. |
| Java 12 | Files.mismatch() compares two files. |
| Java 18 | UTF-8 becomes the default charset (JEP 400). |
| Java 25 | No new file APIs. The new java.lang.IO class simplifies console input and output, not files. |
10. Summary
- File handling lets a program create, read, write and manage files and folders.
- Use
java.nio.file(Path,Files) for most file tasks andjava.iostreams for step-by-step processing. - Use byte streams for binary data and character streams for text, with an explicit charset.
- Close files with try-with-resources and handle
IOException. - Stream large files instead of loading them into memory all at once.