ThePathclass, introduced in JDK7, is the cornerstone of thejava.nio.filepackage — if your application uses file I/O, you will want to learn about the powerful features of this class.
Version Note: If you have pre-JDK7 code that usesjava.io.Fileyou can still take advantage of thePathclass functionality using theFile.toPathmethod. See Legacy File I/O Code for more information.As its name implies, the
Pathclass is a programmatic representation of a path in the file system. APathobject contains the file name and directory list used to construct the path and is used to examine, locate, and manipulate files.A
Pathinstance reflects the underlying platform: on Microsoft Windows, aPathuses the syntax employed by Windows (C:\home\joe\foo) and on Solaris aPathuses the syntax employed by Solaris (/home/joe/foo). APathis not system independent — you can't compare aPathfrom a Solaris file system and expect it to match aPathfrom a Windows file system even if the directory structure is identical and both instances locate the same relative file.The file or directory corresponding to the
Pathmight not exist. As you will see, you can create aPathinstance and manipulate it in a variety of ways: you can append to it, extract pieces of it, compare it to another path. At the appropriate time, you can check the existence of the file corresponding to thePath, create it, open it, delete it, change its permissions, and so on.As you will see, the
Pathclass is "link aware". EveryPathmethod either knows what to do when a symbolic link is encountered or it provides an option allowing you to configure the behavior when a symbolic link is encountered.The
Pathclass offers a rich feature set and is very easy to use. Most of the methods in thePathclass fall into one of two categories:The next sections will examine the
- Path operations. Methods for returning parts of a path, such as the root, name, parent directory and methods for manipulating a path.
- File operations. Methods for opening a file for I/O, creating a file, creating a directory, deleting a file, copying a file, and so on.
Pathclass in detail.