Creating Path Objects with the Paths.get() Method
The Paths utility class provides the get(String first, String… more) static factory method to construct Path objects. In fact, this method invokes the Path.of(String first, String… more) convenience method to obtain a Path.
Path absPath7 = Paths.get(nameSeparator, “a”, “b”, “c”);
Path relPath3 = Paths.get(“c”, “d”);
Creating Path Objects Using the Default File System
We have seen how to obtain the default file system that is accessible to the JVM:
FileSystem dfs = FileSystems.getDefault(); // The default file system
The default file system provides the getPath(String first, String… more) method to construct Path objects. In fact, the Path.of(String first, String… more) method is a convenience method that invokes the FileSystem.getPath() method to obtain a Path object.
Path absPath6 = dfs.getPath(nameSeparator, “a”, “b”, “c”);
Path relPath2 = dfs.getPath(“c”, “d”);
Interoperability with the java.io.File Legacy Class
An object of the legacy class java.io.File can be used to query the file system for information about a file or a directory. The class also provides methods to create, rename, and delete directory entries in the file system. Although there is an overlap of functionality between the Path interface and the File class, the Path interface is recommended over the File class for new code. The interoperability between a File object and a Path object allows the limitations of the legacy class java.io.File to be addressed.
File(String pathname)
Path toPath()
This constructor and this method of the java.io.File class can be used to create a File object from a pathname and to convert a File object to a Path object, respectively.
default File toFile()
This method of the java.nio.file.Path interface can be used to convert a Path object to a File object.
The code below illustrates the round trip between a File object and a Path object:
File file = new File(File.separator + “a” +
File.separator + “b” +
File.separator + “c”); // /a/b/c
// File –> Path, using the java.io.File.toPath() instance method
Path fileToPath = file.toPath(); // /a/b/c
// Path –> File, using the java.nio.file.Path.toFile() default method.
File pathToFile = fileToPath.toFile(); // /a/b/c