Video in progress
What is the difference between java.io.File and java.nio.file.Path, and which one should you use?
File is the old API: it often hides errors by returning false, and its capabilities are limited. Path + Files (Java 7, NIO.2) give precise exceptions, symlinks, attributes and streams. In new code, use Path.
📖 Answer
The biggest difference is error handling.
new File("report.txt").delete(); // returned false. Why? Unknown.
Files.delete(Path.of("report.txt")); // NoSuchFileException or AccessDeniedException
File.delete() reports both a missing file and a missing permission with the same false. On prod this kind of error is hard to track down.
With Path you also get:
resolve,relativize,normalize: safe ways to build paths;Files.walk,Files.lines: streams;- file attributes, permissions, symlinks.
If an old library asks for a File, converting is easy: path.toFile() and file.toPath(). So mixing the two is not a problem, but in the code you write yourself, start from Path.
Sign up to mark studied questions and save your progress.