129. Creating file paths

Starting with JDK 7, we can create a file path via the NIO.2 API. More precisely, a file path can be easily defined via the Path and Paths APIs.

The Path class is a programmatic representation of a path in a filesystem. The path string contains the following information:

  • The filename
  • The directories list
  • The OS-dependent file delimiter (for example, a forward slash / on Solaris and Linux and a backslash on Microsoft Windows)
  • Other allowed characters, for example, the . (current directory) and .. (parent directory) notations
The Path class works with files in different filesystems (FileSystem) that can use different storage places (FileStore is the underlying storage).

A common solution for defining a Path is to call one of the get() methods of the Paths helper class. Another solution relies on the FileSystems.getDefault().getPath() method.

A Path resides in a filesystem—a filesystem stores and organizes files or some form of media, generally on one or more hard drives, in such a way that they can be easily retrieved. The filesystem can be obtained through the final class of java.nio.file.FileSystems, which is used to get an instance of java.nio.file.FileSystem. The default FileSystem of the JVM (commonly known as the default filesystem of the operating system) can be obtained via the FileSystems().getDefault() method. Once we know the filesystem and the location of a file (or directory/folder), we can create a Path object for it.

Another approach consists of creating a Path from a Uniform Resource Identifier (URI). Java wraps a URI via the URI class; then, we can obtain a URI from a String via the URI.create(String uri) method. Furthermore, the Paths class provides a get() method that takes a URI object as an argument and returns the corresponding Path.

Starting with JDK 11, we can create a Path via two of() methods. One of them converts a URI into a Path, while the other one converts a path-string, or a sequence of strings, joined as a path-string.

In the upcoming sections, we'll take a look at the various ways we can create paths.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset