Songs
Songs

Reputation: 269

Path and paths of IO and NIO in java

I'm new at learning about IO and NIO in Java.

And I wonder what

Thank for any explaining.

Upvotes: 1

Views: 2534

Answers (1)

Edwin Buck
Edwin Buck

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:

  1. Path is an interface, so direct calls of its constructor are not possible; as it has no constructor.
  2. 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.
  3. 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:

  1. You don't mess with existing parts of the library in ways that are exposed by the established library call interface (doing this disrupts users of the library, as now they need to rewrite their programs).
  2. You have a backout plan that is easy (this is critical because you might not be able to deliver on time)

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

Related Questions