Java Files Class

Beginner
9 min read
Updated: Nov 2026
3 examples
java.nio.file.Files

Definition and Usage

In Java, java.nio.file.Files is a final class made only of static methods for files and directories. It arrived in Java 7 with the "NIO.2" file API. A Path says where something is; Files does the work: createFile(), copy(), move(), delete(), exists(), readAllLines(), write(), list(), walk(), and many more.

You never write new Files(). Import the class and call the methods on its name. Almost every method declares throws IOException, so main either declares it too or catches it. The Files Methods index lists all 50 guides.

Results can depend on the operating system.

Permissions, hidden files, symbolic links, and owners behave differently on Windows, macOS, and Linux. Method pages label outputs that are not the same everywhere.

Java Syntax

Import Files and Path, build a path, and call static methods with it:

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

Path dir = Paths.get("data");                  // Java 7+; Path.of("data") on Java 11+
Files.createDirectories(dir);                 // make the folder if needed
Path file = dir.resolve("hello.txt");         // data/hello.txt
Files.write(file, "Hi!".getBytes("UTF-8"));   // write 3 bytes
System.out.println(Files.size(file));         // 3

Files vs the Old java.io.File

java.io.File has existed since Java 1.0. Files plus Path is the modern replacement:

Taskjava.io.FileFiles + Path
Report errorsMany methods just return falseThrows a specific IOException subclass
Read or write a whole fileNeeds streams and loopsOne call: readAllLines(), write()
Copy and moveNo copy; renameTo may fail silentlycopy() and move() with options
Walk a folder treeWrite your own recursionwalk(), find(), walkFileTree()
Links, owners, permissionsVery limitedSymbolic links, UserPrincipal, POSIX permissions

Convert between them with file.toPath() and path.toFile().

Working with Path

A java.nio.file.Path is just a name, like a street address: creating one never touches the disk. Get one with Paths.get("a", "b.txt") (Java 7+) or Path.of("a", "b.txt") (Java 11+), and combine paths with dir.resolve("b.txt"). getFileName() returns the last part, getParent() the folder, and dir.relativize(file) the part of file below dir. Windows prints \ between names and other systems print /, which is why the examples print relativize(...).toString().replace('\\', '/').

Exceptions You Will Meet

All of these live in java.nio.file and extend FileSystemException, which extends java.io.IOException:

ExceptionTypical cause
NoSuchFileExceptionThe file or a parent folder is missing, e.g. delete() or size()
FileAlreadyExistsExceptioncreateFile(), createDirectory(), or copy() hits an existing entry
DirectoryNotEmptyExceptionDeleting or replacing a folder that still has entries
AccessDeniedExceptionPermissions forbid it, or (Windows) the file is read-only or in use
NotDirectoryExceptionlist() or newDirectoryStream() was given a regular file

Close Streams with try-with-resources

lines(), list(), walk(), and find() return a lazy Stream, and newDirectoryStream() returns a DirectoryStream. Each keeps a file or folder open until it is closed, so always write try (Stream<Path> s = Files.list(dir)) { ... }. Because they read lazily, an I/O problem in the middle of the stream arrives as an unchecked UncheckedIOException. Directory entries come back in no particular order, so sort them when the order matters.

The Temp-Folder Pattern

To experiment safely, create a scratch folder with createTempDirectory(), build every path with dir.resolve(...), and delete what you made in a finally block: files first, then folders (see deleteIfExists()). Print getFileName() or relative paths, never the full temp path, because its random name and location change on every run and every computer.

Java Examples

Example 1 — Save a Shopping List and Read It Back

Write three lines into a file inside a temporary folder, read them back as a List, and remove both the file and the folder at the end.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

public class FilesHubRoundTrip {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path list = dir.resolve("shopping.txt");
        try {
            Files.write(list, Arrays.asList("bread", "apples", "tea"), StandardCharsets.UTF_8);
            List<String> items = Files.readAllLines(list, StandardCharsets.UTF_8);
            System.out.println("File: " + list.getFileName());
            System.out.println("Items: " + items);
            System.out.println("Second item: " + items.get(1));
        } finally {
            Files.deleteIfExists(list);
            Files.delete(dir);
        }
    }
}

How It Works

  1. A private playground. Files.createTempDirectory("demo") makes a new, empty folder with a unique name under the system temp location, so the program never touches your real files.
  2. Build the path, then use it. dir.resolve("shopping.txt") only joins names; nothing exists on disk until Files.write creates the file and writes each list element as one line.
  3. Read it back. Files.readAllLines splits the content at the line breaks and returns the three items, so items.get(1) is apples.
  4. Always tidy up. The finally block deletes the file and then the now-empty folder, even if reading had failed.

Example 2 — List a Folder in a Predictable Order

Create a few entries, then list the folder with Files.list inside try-with-resources. The names are sorted before printing because the operating system may return them in any order.

Java
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 FilesHubListing {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path photos = Files.createDirectory(dir.resolve("photos"));
        Path todo = Files.createFile(dir.resolve("todo.txt"));
        Path budget = Files.createFile(dir.resolve("budget.csv"));
        List<String> names;
        try (Stream<Path> entries = Files.list(dir)) {
            names = entries.map(p -> p.getFileName() + (Files.isDirectory(p) ? "/" : ""))
                           .sorted()
                           .collect(Collectors.toList());
        }
        System.out.println(names);
        Files.delete(budget);
        Files.delete(todo);
        Files.delete(photos);
        Files.delete(dir);
        System.out.println("Cleaned up: " + Files.notExists(dir));
    }
}

How It Works

  1. Three kinds of setup. createDirectory adds a subfolder and createFile adds two empty files; each call returns the Path it created, which is kept for the cleanup later.
  2. A stream that must be closed. Files.list holds an open directory handle, so it sits in a try-with-resources header and is closed as soon as the names are collected.
  3. Mark folders, then sort. Each entry becomes its file name plus a trailing slash for directories, and sorted() puts the strings in alphabetical order so every system prints the same line.
  4. Delete inside-out. The two files and the subfolder go first, because Files.delete refuses to remove a folder that still has entries; notExists then confirms the temp folder is gone.

Example 3 — Catch the Specific Exceptions Files Throws

Trigger three common failures on purpose and catch each one by its own exception class. All of them extend IOException.

Java
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class FilesHubErrors {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path report = Files.createFile(dir.resolve("report.txt"));
        try {
            Files.createFile(report);
        } catch (FileAlreadyExistsException e) {
            System.out.println("createFile: report.txt is already there");
        }
        try {
            Files.delete(dir.resolve("missing.txt"));
        } catch (NoSuchFileException e) {
            System.out.println("delete: missing.txt was not found");
        }
        try {
            Files.delete(dir);
        } catch (DirectoryNotEmptyException e) {
            System.out.println("delete: the folder still contains report.txt");
        }
        Files.delete(report);
        Files.delete(dir);
        System.out.println("Done");
    }
}

How It Works

  1. Create twice. The second createFile on the same path fails with FileAlreadyExistsException; the existing file is left untouched.
  2. Delete something absent. Files.delete on a name that was never created throws NoSuchFileException. Use deleteIfExists when a missing file is fine.
  3. Delete a full folder. The temp folder still holds report.txt, so deleting it throws DirectoryNotEmptyException instead of silently removing the contents.
  4. Specific first, general later. Each catch names one subclass of IOException, so the program can react differently to each problem; anything unexpected still escapes through throws IOException.

Next: Java Files Methods by Group

Full list with short descriptions: Java Files Methods index.

Frequently Asked Questions

A final utility class, added in Java 7 as part of NIO.2, with only static methods for working with files and directories: creating, copying, moving, deleting, checking, reading, writing, listing, and reading or changing attributes.
Prefer Files with Path for new code. Many java.io.File methods just return false when something fails, while Files throws specific exceptions such as NoSuchFileException.
They do the same thing. Paths.get works on Java 7 and later; Path.of was added in Java 11. The examples here use Paths.get or Files.createTempDirectory so they compile on Java 8.
Those streams keep a directory handle open. Put them in try-with-resources; otherwise the handle may leak, and on Windows it can stop you from deleting the folder.
Yes for the overloads without a Charset parameter, such as readAllLines(path), lines(path), and write(path, lines) from Java 8, and readString and writeString from Java 11. The Java 7 overloads take an explicit Charset.

Browse every Files method

Open the methods index for categorized guides with runnable temp-folder examples and FAQs.

Files Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful