ThePath
class, introduced in JDK7, is the cornerstone of thejava.nio.file
package — 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.File
you can still take advantage of thePath
class functionality using theFile.toPath
method. See Legacy File I/O Code for more information.As its name implies, the
Path
class is a programmatic representation of a path in the file system. APath
object contains the file name and directory list used to construct the path and is used to examine, locate, and manipulate files.A
Path
instance reflects the underlying platform: on Microsoft Windows, aPath
uses the syntax employed by Windows (C:\home\joe\foo
) and on Solaris aPath
uses the syntax employed by Solaris (/home/joe/foo
). APath
is not system independent — you can't compare aPath
from a Solaris file system and expect it to match aPath
from 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
Path
might not exist. As you will see, you can create aPath
instance 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
Path
class is "link aware". EveryPath
method 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
Path
class offers a rich feature set and is very easy to use. Most of the methods in thePath
class 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.
Path
class in detail.