Reputation: 269
I'm new at learning about IO and NIO in Java.
And I wonder what
java.nio.file.Path
and java.nio.file.Paths
?Path
and Paths
?Thank for any explaining.
Upvotes: 1
Views: 2534
Reputation: 70979
Path is a class that represents a path. Anything where you typically already have a Path
involves the methods located here.
Paths is a set of utilities. These utilities produce Path
objects from other types of input. The utilities do not require having a Path
ahead of time. They are convenience wrappers for common, often repeatedly used code, to reduce the need to cut-and-paste.
Here is an example of using Paths
:
/* I have a String, but need a Path */
Path path = Paths.get("/home/user/.config");
Here is an example of using Path
:
/* I have a Path, but need a String */
String name = path.toString();
The reason why a Utility class like Paths
is required is a combination of a number of factors:
Path
is an interface, so direct calls of its constructor are not possible; as it has no constructor.String
is a final class, and a class where modifying it would probably be far more difficult to present as an alternative than creating a utility class. So while "/home/user/.config".toPath()
might be a valid object-oriented way of doing things, legacy code prevents adding that without more deliberation.URI
has pressures on it similar to the pressures described above on String
.When they added in the NIO Path
class, they wanted their code to be reviewed and integrated into the core Java library.
Stuff that is easy to get others to add to a library has the following characteristics:
If they took the approach of modifying String
and URI
to have a getPath(...)
function, then they would have increased the difficulty in getting their code integrated into the Java standard library.
Upvotes: 2