原文链接:Java – Path vs File
1. Overview
In Java, Path and File are classes responsible for file I/O operations. They perform the same functions but belong to different packages.
In this tutorial, we'll discuss the differences between these two classes. We'll start with a quick class recap. Then, we'll talk about some legacy drawbacks. Finally, we'll learn how to migrate functionalities between both APIs.
2. java.io.File Class
Since the very first versions, Java has delivered its own java.io package, which contains nearly every class we might ever need to perform input and output operations. The File class is an abstract representation of file and directory pathnames:
File file = new File("baeldung/tutorial.txt");
Instances of the File class are immutable – once created, the abstract pathname represented by this object will never change.
3. java.nio.file.Path Class
The Path class forms part of the NIO2 update, which came to Java with version 7. It delivers an entirely new API to work with I/O. Moreover, like the legacy File class, Path also creates an object that may be used to locate a file in a file system.
Likewise, it can perform all the operations that can be done with the File class:
Path path = Paths.get("baeldung/tutorial.txt");
Instead of using a constructor as we do with the File API, we create a Path instance using the static java.nio.file.Paths.get() method.
4. File Class Drawbacks
After this short recap of the two classes, let's now discuss both APIs and answer the question: If they deliver the same func