Path vs File in Java

Naveen AnamaneniUpdated · 4 min read

java.io.File and java.nio.file.Path both represent a file or folder location. File is the original class from Java 1.0; Path is part of NIO.2, added in Java 7 to fix File's weaknesses. The biggest practical difference is error handling: many File methods report failure by quietly returning false, while Files methods throw an exception that says exactly what went wrong. In this lesson, you will compare them side by side.

Example: The Same Failure, Two Ways

Let's see an example that tries to delete a file that doesn't exist.

DeleteCompare.java▶ Try it
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
public class DeleteCompare {
    public static void main(String[] args) {
        File oldWay = new File("missing.txt");
        boolean deleted = oldWay.delete();
        System.out.println("File.delete() returned " + deleted);
 
        try {
            Files.delete(Path.of("missing.txt"));
        } catch (IOException e) {
            System.out.println("Files.delete() threw "
                + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
}
Output
File.delete() returned false
Files.delete() threw NoSuchFileException: missing.txt

Explanation: File.delete() returns false, but it doesn't say why: the file might be missing, locked, or not allowed. Files.delete throws NoSuchFileException, which names the exact problem. With File, it's also easy to forget to check the returned boolean at all.

Differences Between File and Path

java.io.Filejava.nio.file.Path + Files
Packagejava.iojava.nio.file
IntroducedJava 1.0Java 7
TypeA classAn interface (plus the Files utility class)
Error reportingMany methods return booleanDescriptive exceptions
Symbolic linksNot supported properlyFull support
File attributes and permissionsVery limitedFull (readAttributes, POSIX permissions)
Reading and writing whole filesNot built inreadString, writeString, readAllLines
Walking a treeManual recursion with listFiles()Files.walk, Files.find
Watching foldersNoWatchService
Path operationsFewresolve, relativize, normalize

Converting Between Them

Convert.java▶ Try it
import java.io.File;
import java.nio.file.Path;
 
public class Convert {
    public static void main(String[] args) {
        File file = new File("reports", "marks.csv");
        Path path = file.toPath();
        File back = path.toFile();
 
        System.out.println(file + " -> " + path + " -> " + back);
        System.out.println(path.getFileName() + " in " + path.getParent());
    }
}
Output
reports/marks.csv -> reports/marks.csv -> reports/marks.csv
marks.csv in reports

Explanation: file.toPath() and path.toFile() convert in either direction with no loss, so you can use Path in your own code and still call older libraries that need a File.

Common Mistakes

Ignoring the boolean result of File.delete(), mkdir() or renameTo(). Failures go unnoticed.

Using File.renameTo to move files across disks. It often fails silently; use Files.move.

Thinking Path is a class. It's an interface; create paths with Path.of.

Interview Corner

Why is Path preferred over File?

NIO.2's Path with Files reports failures through specific exceptions instead of false return values, supports symbolic links, file attributes and permissions, offers convenient methods to read and write whole files and to walk directory trees, provides path operations such as resolve and normalize, and works with WatchService. java.io.File lacks most of these and makes silent failures easy. The two convert with toPath() and toFile().

Practice

  1. Easy: Try new File("a/b/c").mkdir() and Files.createDirectory(Path.of("a/b/c")) when a/b doesn't exist, and compare what each reports.
  2. Harder: Rewrite a method that lists the .txt files in a folder using File.listFiles() so that it uses Files.list and a stream instead.

Quick check: Path vs File

4 questions
1What does File.delete() return when it fails?
2What does Files.delete throw for a missing file?
3How do you convert a Path to a File?
4Which supports symbolic links properly?

Key Takeaways

Was this tutorial helpful?

Lesson 355 of 482