Java - end of the road for Paths

Java introduced NIO 2 APIs with version 1.7. I wrote an article several years ago, after seeing not many developers make use of the new API. With this API, you would use java.nio.file.Path instead of to represent a file.

To get an instance of Path one had to use java.nio.file.Paths as follows.

Path path = Paths.get("/Users/naresha/temp/readme.txt");
System.out.println(path.getFileName()); // println readme.txt

There was one thing that took me a while to get used to. If I want to work with the path object, I could do it as follows.

Stream<String> lines = Files.lines(path);

As you would have noticed, all those methods to work with Path objects are present in class java.nio.file.Files, while I would expect them in java.nio.file.Paths. Paths needed only to get an instance of Path.

With Java 11, you don't need the Paths class anymore. Now you can get an instance of Path as follows.

Path path = Path.of("/Users/naresha/temp/readme.txt");

Also, the method Paths.get now delegates to Path.of. The documentation of Paths recommends the use of Path.of and mentions the possibilities of it getting deprecated in the future. Well, this wouldn't have been possible without the support for static methods in interfaces (note that Path is an interface). So obviously they couldn't have thought about this design in Java 1.7.

Show Comments