Java File Handling

Java file handling means creating, reading, writing, and managing files from a Java program. Modern Java code usually uses Path and the Files utility class from the java.nio.file package.

File operations can fail for many reasons, such as missing files, permission problems, or a full disk. For that reason, many file methods throw IOException.

Paths and Files

A Path represents the location of a file or directory. The Files class contains static methods that work with paths, such as write, readAllLines, readString, exists, and deleteIfExists.

This example creates a temporary file, writes two lines to it, reads the lines back, and then deletes the file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("tasks", ".txt");

        Files.write(file, List.of("Learn Java", "Practice files"));

        List<String> lines = Files.readAllLines(file);
        System.out.println("First task: " + lines.get(0));
        System.out.print("Line count: " + lines.size());

        Files.deleteIfExists(file);
    }
}

Output:

First task: Learn Java
Line count: 2

Files.createTempFile creates a real file in the system temporary directory. Files.write stores the list as lines of text, and Files.readAllLines reads the file back into a List<String>.

Writing and Appending Text

Files.writeString is convenient when you want to write one string. By default, writing to an existing file replaces its contents. To add to the end of a file, pass StandardOpenOption.APPEND.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("scores", ".txt");

        Files.writeString(file, "Ava: 91\n");
        Files.writeString(file, "Noah: 84", StandardOpenOption.APPEND);

        String text = Files.readString(file);
        System.out.print(text);

        Files.deleteIfExists(file);
    }
}

Output:

Ava: 91
Noah: 84

The first call writes the original contents. The second call uses APPEND, so Java adds the new text after the existing text instead of replacing it.

Checking Files

Before reading from a path, you can check what it points to. Files.exists(path) checks whether something is there, Files.isRegularFile(path) checks for a normal file, and Files.isDirectory(path) checks for a directory.

Method Purpose
Files.exists(path) Checks whether the path exists
Files.isRegularFile(path) Checks whether the path is a normal file
Files.isDirectory(path) Checks whether the path is a directory
Files.size(path) Returns the file size in bytes
Files.deleteIfExists(path) Deletes the file if it exists

Listing a Directory

A directory contains other files and directories. Files.list returns a stream of paths, so use try-with-resources to close that stream after use.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws IOException {
        Path folder = Files.createTempDirectory("demo-folder");
        Files.writeString(folder.resolve("readme.txt"), "Hello");
        Files.writeString(folder.resolve("data.txt"), "42");

        try (Stream<Path> entries = Files.list(folder)) {
            List<String> names = entries
                    .map(path -> path.getFileName().toString())
                    .sorted()
                    .collect(Collectors.toList());

            System.out.print(names);
        }

        Files.deleteIfExists(folder.resolve("readme.txt"));
        Files.deleteIfExists(folder.resolve("data.txt"));
        Files.deleteIfExists(folder);
    }
}

Output:

[data.txt, readme.txt]

folder.resolve("readme.txt") creates a path inside the folder. The stream maps each path to its file name, sorts the names, and collects them into a list before printing.

Handling IOException

The examples use throws IOException on main to keep the focus on file handling. In larger programs, you often catch IOException and show a helpful message or choose another action.

  • Use Path and Files for modern file handling.
  • Use try-with-resources for streams returned by file methods.
  • Be ready for IOException whenever your program touches the file system.
  • Delete temporary files when you no longer need them.

Takeaway: Java file handling is built around paths, file utility methods, and careful exception handling for operations that depend on the file system.