00:00

File Handling in Java: Reading, Writing and Managing Files

Last updated:

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.

Java file handling APIs: java.io and java.nio.fileTwo panels. The java.io package, available since Java 1.0, contains File for naming and checking files and folders, the byte streams InputStream and OutputStream for raw binary data, and the character streams Reader and Writer for text. The java.nio.file package, added in Java 7, contains Path for a file-system location, Files for one-call operations such as read, write, copy, move, delete and list, and the older Paths factory. File.toPath() converts a File to a Path, and Path.toFile() converts back.java.ioClassic API, Java 1.0+FileNames a file or folder and checks it:exists(), length(), mkdir(), delete()InputStream / OutputStreamByte streams: read and write raw bytes,for images, PDFs and ZIP filesReader / WriterCharacter streams (Java 1.1): read andwrite text, decoded with a charsetjava.nio.fileNIO.2, Java 7+PathA location in the file system,created with Path.of() (Java 11)FilesStatic helpers that read, write, copy,move, delete and list in one callPaths (older factory)Paths.get() also creates a Path;Path.of() is now recommendedtoPath()toFile()

Swipe sideways to see the whole diagram.

PackageKey typesBest for
java.ioFile, byte streams, character streamsProcessing data in a stream, working with older APIs
java.nio.file (NIO.2)Path, FilesMost 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

TaskClassic java.ioModern java.nio.file
Refer to a filenew File("notes.txt")Path.of("notes.txt")
Check that it existsfile.exists()Files.exists(path)
Write textFileWriter + BufferedWriterFiles.writeString(path, text)
Read all linesBufferedReader.readLine() in a loopFiles.readAllLines(path)
Read raw bytesFileInputStreamFiles.readAllBytes(path)
Copy a fileRead and write through streamsFiles.copy(source, target)
Delete a filefile.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.

GroceryListFile.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 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));
    }
}
Output
File exists: true
Items: 4
1. Rice
2. Lentils
3. Tomatoes
4. Curd
Deleted: true

How the code works

  1. Files.createTempDirectory() creates a new, empty folder, and resolve() builds the path of list.txt inside it.
  2. Files.write() creates the file and writes each list element as a line. Text is encoded as UTF-8.
  3. Files.writeString() with StandardOpenOption.APPEND adds a line to the end instead of replacing the content.
  4. Files.readAllLines() returns every line as a List<String>, which suits small files.
  5. 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.

LogErrorCounter.java
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());
    }
}
Output
Found: 10:05 ERROR Disk quota exceeded
Found: 10:12 ERROR Connection reset
Error lines: 2
Deleted: true

How the code works

  1. File.createTempFile() creates an empty file with a unique name.
  2. FileWriter turns characters into bytes using the given charset, and BufferedWriter collects them so data is written in larger, faster chunks. newLine() adds the platform's line separator.
  3. BufferedReader.readLine() returns one line at a time and null at the end of the file.
  4. 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_8 when your code must also run on Java 17 or earlier.
  • Loading huge files into memory. readAllLines() and readAllBytes() suit small files; stream large ones line by line.
  • Ignoring the result of File.delete(). It returns false instead 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 versionChange
Java 1.0 and 1.1java.io with File and byte streams; Reader and Writer added in 1.1.
Java 7NIO.2 (Path, Files) and try-with-resources.
Java 8Files.lines(), Files.list() and BufferedReader.lines() return streams.
Java 11Files.readString(), Files.writeString() and Path.of(); charset constructors for FileReader and FileWriter.
Java 12Files.mismatch() compares two files.
Java 18UTF-8 becomes the default charset (JEP 400).
Java 25No 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 and java.io streams 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.

Related Tutorials

11. Official Java Documentation References