Spec-Zone .ru
спецификации, руководства, описания, API
Please note that the specifications and other information contained herein are not final and are subject to change. The information is being made available to you solely for purpose of evaluation.

Java™ Platform
Standard Ed. 7

DRAFT ea-b118

java.nio.file
Class Path

java.lang.Object
  extended by java.nio.file.Path
All Implemented Interfaces:
Comparable<Path>, Iterable<Path>, FileRef, Watchable

public abstract class Path
extends Object
implements FileRef, Comparable<Path>, Iterable<Path>, Watchable

A file reference that locates a file using a system dependent path. The file is not required to exist.

On many platforms a path is the means to locate and access files in a file system. A path is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter.

Path operations

A system dependent path represented by this class is conceptually a sequence of name elements and optionally a root component. The name that is farthest from the root of the directory hierarchy is the name of a file or directory. The other elements are directory names. The root component typically identifies a file system hierarchy. A Path can represent a root, a root and a sequence of names, or simply one or more name elements. It defines the getName, getParent, getRoot, and subpath methods to access the components or a subsequence of its name elements.

In addition to accessing the components of a path, a Path also defines resolve and relativize operations. Paths can also be compared, and tested against each other using using the startsWith and endWith methods.

File operations

A Path is either absolute or relative. An absolute path is complete in that does not need to be combined with another path in order to locate a file. All operations on relative paths are first resolved against a file system's default directory as if by invoking the toAbsolutePath method.

In addition to the operations defined by the FileRef interface, this class defines the following operations:

This class implements Watchable interface so that a directory located by a path can be registered with a WatchService. and entries in the directory watched.

File attributes

In addition to the setAttribute and getAttribute methods, the java.nio.file.attribute package provides type-safe and efficient access to file attributes or meta-data associated with files. The Attributes class defines methods that operate on or return file attributes. For example, the file type, size, timestamps, and other basic meta-data are obtained, in bulk, by invoking the Attributes.readBasicFileAttributes method:
     Path file = ...
     BasicFileAttributes attrs = Attributes.readBasicFileAttributes(file);
 

Interoperability

Paths created by file systems associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The File.toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object.

Path objects created by file systems associated with the default provider are interoperable with objects created by other file systems created by the same provider. Path objects created by file systems associated with other providers may not be interoperable with other file systems created by the same provider. The reasons for this are provider specific.

Concurrency

Instances of this class are immutable and safe for use by multiple concurrent threads.

Since:
1.7

Constructor Summary
Modifier Constructor and Description
protected Path()
          Initializes a new instance of this class.
 
Method Summary
Modifier and Type Method and Description
abstract  void checkAccess(AccessMode... modes)
          Checks the existence and optionally the accessibility of the file located by this path.
abstract  int compareTo(Path other)
          Compares two abstract paths lexicographically.
abstract  Path copyTo(Path target, CopyOption... options)
          Copy the file located by this path to a target location.
abstract  Path createDirectory(FileAttribute<?>... attrs)
          Creates a new directory.
abstract  Path createFile(FileAttribute<?>... attrs)
          Creates a new and empty file, failing if the file already exists.
abstract  Path createLink(Path existing)
          Creates a new link (directory entry) for an existing file (optional operation).
abstract  Path createSymbolicLink(Path target, FileAttribute<?>... attrs)
          Creates a symbolic link to a target (optional operation).
abstract  void delete()
          Deletes the file located by this path.
abstract  void deleteIfExists()
          Deletes the file located by this path, if it exists.
abstract  boolean endsWith(Path other)
          Tests if this path ends with the given path.
abstract  boolean equals(Object other)
          Tests this path for equality with the given object.
abstract  boolean exists()
          Tests whether the file located by this path exists.
abstract  FileStore getFileStore()
          Returns the FileStore representing the file store where an existing file, located by this path, is stored.
abstract  FileSystem getFileSystem()
          Returns the file system that created this object.
abstract  Path getName()
          Returns the name of the file or directory denoted by this path.
abstract  Path getName(int index)
          Returns a name element of this path.
abstract  int getNameCount()
          Returns the number of name elements in the path.
abstract  Path getParent()
          Returns the parent path, or null if this path does not have a parent.
abstract  Path getRoot()
          Returns the root component of this path as a Path object, or null if this path does not have a root component.
abstract  int hashCode()
          Computes a hash code for this path.
abstract  boolean isAbsolute()
          Tells whether or not this path is absolute.
abstract  boolean isHidden()
          Tells whether or not the file located by this object is considered hidden.
abstract  boolean isSameFile(Path other)
          Tests if the file referenced by this object is the same file referenced by another object.
abstract  Iterator<Path> iterator()
          Returns an iterator over the name elements of this path.
abstract  Path moveTo(Path target, CopyOption... options)
          Move or rename the file located by this path to a target location.
abstract  SeekableByteChannel newByteChannel(OpenOption... options)
          Opens or creates a file, returning a seekable byte channel to access the file.
abstract  SeekableByteChannel newByteChannel(Set<? extends OpenOption> options, FileAttribute<?>... attrs)
          Opens or creates a file, returning a seekable byte channel to access the file.
abstract  DirectoryStream<Path> newDirectoryStream()
          Opens the directory referenced by this object, returning a DirectoryStream to iterate over all entries in the directory.
abstract  DirectoryStream<Path> newDirectoryStream(DirectoryStream.Filter<? super Path> filter)
          Opens the directory referenced by this object, returning a DirectoryStream to iterate over the entries in the directory.
abstract  DirectoryStream<Path> newDirectoryStream(String glob)
          Opens the directory referenced by this object, returning a DirectoryStream to iterate over the entries in the directory.
abstract  OutputStream newOutputStream(OpenOption... options)
          Opens or creates the file located by this object for writing, returning an output stream to write bytes to the file.
abstract  Path normalize()
          Returns a path that is this path with redundant name elements eliminated.
abstract  boolean notExists()
          Tests whether the file located by this path does not exist.
abstract  Path readSymbolicLink()
          Reads the target of a symbolic link (optional operation).
abstract  WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events)
          Registers the file located by this path with a watch service.
abstract  WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
          Registers the file located by this path with a watch service.
abstract  Path relativize(Path other)
          Constructs a relative path between this path and a given path.
abstract  Path resolve(Path other)
          Resolve the given path against this path.
abstract  Path resolve(String other)
          Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method.
abstract  boolean startsWith(Path other)
          Tests if this path starts with the given path.
abstract  Path subpath(int beginIndex, int endIndex)
          Returns a relative Path that is a subsequence of the name elements of this path.
abstract  Path toAbsolutePath()
          Returns a Path object representing the absolute path of this path.
abstract  Path toRealPath(boolean resolveLinks)
          Returns the real path of an existing file.
abstract  String toString()
          Returns the string representation of this path.
abstract  URI toUri()
          Returns a URI to represent this path.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface java.nio.file.FileRef
getAttribute, getFileAttributeView, newInputStream, readAttributes, setAttribute
 

Constructor Detail

Path

protected Path()
Initializes a new instance of this class.

Method Detail

getFileSystem

public abstract FileSystem getFileSystem()
Returns the file system that created this object.

Returns:
the file system that created this object

isAbsolute

public abstract boolean isAbsolute()
Tells whether or not this path is absolute.

An absolute path is complete in that it doesn't need to be combined with other path information in order to locate a file.

Returns:
true if, and only if, this path is absolute

getRoot

public abstract Path getRoot()
Returns the root component of this path as a Path object, or null if this path does not have a root component.

Returns:
a path representing the root component of this path, or null

getName

public abstract Path getName()
Returns the name of the file or directory denoted by this path. The file name is the farthest element from the root in the directory hierarchy.

Returns:
a path representing the name of the file or directory, or null if this path has zero elements

getParent

public abstract Path getParent()
Returns the parent path, or null if this path does not have a parent.

The parent of this path object consists of this path's root component, if any, and each element in the path except for the farthest from the root in the directory hierarchy. This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as "." and ".." that may be used in some implementations. On UNIX for example, the parent of "/a/b/c" is "/a/b", and the parent of "x/y/." is "x/y". This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.

If this path has one or more elements, and no root component, then this method is equivalent to evaluating the expression:

 subpath(0, getNameCount()-1);
 

Returns:
a path representing the path's parent

getNameCount

public abstract int getNameCount()
Returns the number of name elements in the path.

Returns:
the number of elements in the path, or 0 if this path only represents a root component

getName

public abstract Path getName(int index)
Returns a name element of this path.

The index parameter is the index of the name element to return. The element that is closest to the root in the directory hierarchy has index 0. The element that is farthest from the root has index count-1.

Parameters:
index - the index of the element
Returns:
the name element
Throws:
IllegalArgumentException - if index is negative, index is greater than or equal to the number of elements, or this path has zero name elements

subpath

public abstract Path subpath(int beginIndex,
                             int endIndex)
Returns a relative Path that is a subsequence of the name elements of this path.

The beginIndex and endIndex parameters specify the subsequence of name elements. The name that is closest to the root in the directory hierarchy has index 0. The name that is farthest from the root has index count-1. The returned Path object has the name elements that begin at beginIndex and extend to the element at index endIndex-1.

Parameters:
beginIndex - the index of the first element, inclusive
endIndex - the index of the last element, exclusive
Returns:
a new Path object that is a subsequence of the name elements in this Path
Throws:
IllegalArgumentException - if beginIndex is negative, or greater than or equal to the number of elements. If endIndex is less than or equal to beginIndex, or larger than the number of elements.

startsWith

public abstract boolean startsWith(Path other)
Tests if this path starts with the given path.

This path starts with the given path if this path's root component starts with the root component of the given path, and this path starts with the same name elements as the given path. If the given path has more name elements than this path then false is returned.

Whether or not the root component of this path starts with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not start with the given path.

Parameters:
other - the given path
Returns:
true if this path starts with the given path; otherwise false

endsWith

public abstract boolean endsWith(Path other)
Tests if this path ends with the given path.

If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.

If the given path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is file system specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.

Parameters:
other - the given path
Returns:
true if this path ends with the given path; otherwise false

normalize

public abstract Path normalize()
Returns a path that is this path with redundant name elements eliminated.

The precise definition of this method is implementation dependent but in general it derives from this path, a path that does not contain redundant name elements. In many file systems, the "." and ".." are special names used to indicate the current directory and parent directory. In such file systems all occurrences of "." are considered redundant. If a ".." is preceded by a non-".." name then both names are considered redundant (the process to identify such names is repeated until is it no longer applicable).

This method does not access the file system; the path may not locate a file that exists. Eliminating ".." and a preceding name from a path may result in the path that locates a different file than the original path. This can arise when the preceding name is a symbolic link.

Returns:
the resulting path, or this path if it does not contain redundant name elements, or null if this path does not have a root component and all name elements are redundant
See Also:
getParent(), toRealPath(boolean)

resolve

public abstract Path resolve(Path other)
Resolve the given path against this path.

If the other parameter is an absolute path then this method trivially returns other. If other is null then this path is returned. Otherwise this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified.

Parameters:
other - the path to resolve against this path; can be null
Returns:
the resulting path
See Also:
relativize(java.nio.file.Path)

resolve

public abstract Path resolve(String other)
Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method.

Parameters:
other - the path string to resolve against this path
Returns:
the resulting path
Throws:
InvalidPathException - If the path string cannot be converted to a Path.
See Also:
FileSystem.getPath(java.lang.String)

relativize

public abstract Path relativize(Path other)
Constructs a relative path between this path and a given path.

Relativization is the inverse of resolution. This method attempts to construct a relative path that when resolved against this path, yields a path that locates the same file as the given path. For example, on UNIX, if this path is "/a/b" and the given path is "/a/b/c/d" then the resulting relative path would be "c/d". Where this path and the given path do not have a root component, then a relative path can be constructed. A relative path cannot be constructed if only one of the paths have a root component. Where both paths have a root component then it is implementation dependent if a relative path can be constructed. If this path and the given path are equal then null is returned.

For any two paths p and q, where q does not have a root component,

p.relativize(p.resolve(q)).equals(q)

When symbolic links are supported, then whether the resulting path, when resolved against this path, yields a path that can be used to locate the same file as other is implementation dependent. For example, if this path is "/a/b" and the given path is "/a/x" then the resulting relative path may be "../x". If "b" is a symbolic link then is implementation dependent if "a/b/../x" would locate the same file as "/a/x".

Parameters:
other - the path to relativize against this path
Returns:
the resulting relative path, or null if both paths are equal
Throws:
IllegalArgumentException - if other is not a Path that can be relativized against this path

delete

public abstract void delete()
                     throws IOException
Deletes the file located by this path.

An implementation may require to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted.

If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.

On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.

Throws:
NoSuchFileException - if the file does not exist (optional specific exception)
DirectoryNotEmptyException - if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the SecurityManager.checkDelete(String) method is invoked to check delete access to the file

deleteIfExists

public abstract void deleteIfExists()
                             throws IOException
Deletes the file located by this path, if it exists.

As with the delete() method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.

If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.

On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.

Throws:
DirectoryNotEmptyException - if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the SecurityManager.checkDelete(String) method is invoked to check delete access to the file.

createSymbolicLink

public abstract Path createSymbolicLink(Path target,
                                        FileAttribute<?>... attrs)
                                 throws IOException
Creates a symbolic link to a target (optional operation).

The target parameter is the target of the link. It may be an absolute or relative path and may not exist. When the target is a relative path then file system operations on the resulting link are relative to the path of the link.

The attrs parameter is an optional array of attributes to set atomically when creating the link. Each attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

Where symbolic links are supported, but the underlying FileStore does not support symbolic links, then this may fail with an IOException. Additionally, some operating systems may require that the Java virtual machine be started with implementation specific privileges to create symbolic links, in which case this method may throw IOException.

Parameters:
target - the target of the symbolic link
attrs - the array of attributes to set atomically when creating the symbolic link
Returns:
this path
Throws:
UnsupportedOperationException - if the implementation does not support symbolic links or the array contains an attribute that cannot be set atomically when creating the symbolic link
FileAlreadyExistsException - if a file with the name already exists (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, it denies LinkPermission("symbolic") or its checkWrite method denies write access to the path of the symbolic link.

createLink

public abstract Path createLink(Path existing)
                         throws IOException
Creates a new link (directory entry) for an existing file (optional operation).

This path locates the directory entry to create. The existing parameter is the path to an existing file. This method creates a new directory entry for the file so that it can be accessed using this path. On some file systems this is known as creating a "hard link". Whether the file attributes are maintained for the file or for each directory entry is file system specific and therefore not specified. Typically, a file system requires that all links (directory entries) for a file be on the same file system. Furthermore, on some platforms, the Java virtual machine may require to be started with implementation specific privileges to create hard links or to create links to directories.

Parameters:
existing - a reference to an existing file
Returns:
this path
Throws:
UnsupportedOperationException - if the implementation does not support adding an existing file to a directory
FileAlreadyExistsException - if the entry could not otherwise be created because a file of that name already exists (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, it denies LinkPermission("hard") or its checkWrite method denies write access to both this path and the path of the existing file.

readSymbolicLink

public abstract Path readSymbolicLink()
                               throws IOException
Reads the target of a symbolic link (optional operation).

If the file system supports symbolic links then this method is used to read the target of the link, failing if the file is not a symbolic link. The target of the link need not exist. The returned Path object will be associated with the same file system as this Path.

Returns:
a Path object representing the target of the link
Throws:
UnsupportedOperationException - if the implementation does not support symbolic links
NotLinkException - if the target could otherwise not be read because the file is not a symbolic link (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, it checks that FilePermission has been granted with the "readlink" action to read the link.

toUri

public abstract URI toUri()
Returns a URI to represent this path.

This method constructs a hierarchical URI that is absolute with a non-empty path component. Its scheme is equal to the URI scheme that identifies the provider. The exact form of the other URI components is highly provider dependent. In particular, it is implementation dependent if its query, fragment, and authority components are defined or undefined.

For the default provider the path component will represent the absolute path; the query, fragment components are undefined. Whether the authority component is defined or not is implementation dependent. There is no guarantee that the URI may be used to construct a java.io.File. In particular, if this path represents a Universal Naming Convention (UNC) path, then the UNC server name may be encoded in the authority component of the resulting URI. In the case of the default provider, and the file exists, and it can be determined that the file is a directory, then the resulting URI will end with a slash.

The default provider provides a similar round-trip guarantee to the File class. For a given Path p it is guaranteed that

Paths.get(p.toUri()).equals(p .toAbsolutePath())
so long as the original Path, the URI, and the new Path are all created in (possibly different invocations of) the same Java virtual machine. Whether other providers make any guarantees is provider specific and therefore unspecified.

When a file system is constructed to access the contents of a file as a file system then it is highly implementation specific if the returned URI represents the given path in the file system or it represents a compound URI that encodes the URI of the enclosing file system. A format for compound URIs is not defined in this release; such a scheme may be added in a future release.

Returns:
an absolute, hierarchical URI with a non-empty path component
Throws:
IOError - if an I/O error occurs obtaining the absolute path, or where a file system is constructed to access the contents of a file as a file system, and the URI of the enclosing file system cannot be obtained
SecurityException - In the case of the default provider, and a security manager is installed, the toAbsolutePath method throws a security exception.

toAbsolutePath

public abstract Path toAbsolutePath()
Returns a Path object representing the absolute path of this path.

If this path is already absolute then this method simply returns this path. Otherwise, this method resolves the path in an implementation dependent manner, typically by resolving the path against a file system default directory. Depending on the implementation, this method may throw an I/O error if the file system is not accessible.

Returns:
a Path object representing the absolute path
Throws:
IOError - if an I/O error occurs
SecurityException - In the case of the default provider, a security manager is installed, and this path is not absolute, then the security manager's checkPropertyAccess method is invoked to check access to the system property user.dir

toRealPath

public abstract Path toRealPath(boolean resolveLinks)
                         throws IOException
Returns the real path of an existing file.

The precise definition of this method is implementation dependent but in general it derives from this path, an absolute path that locates the same file as this path, but with name elements that represent the actual name of the directories and the file. For example, where filename comparisons on a file system are case insensitive then the name elements represent the names in their actual case. Additionally, the resulting path has redundant name elements removed.

If this path is relative then its absolute path is first obtained, as if by invoking the toAbsolutePath method.

The resolveLinks parameter specifies if symbolic links should be resolved. This parameter is ignored when symbolic links are not supported. Where supported, and the parameter has the value true then symbolic links are resolved to their final target. Where the parameter has the value false then this method does not resolve symbolic links. Some implementations allow special names such as ".." to refer to the parent directory. When deriving the real path, and a ".." (or equivalent) is preceded by a non-".." name then an implementation will typically causes both names to be removed. When not resolving symbolic links and the preceding name is a symbolic link then the names are only removed if it guaranteed that the resulting path will locate the same file as this path.

Returns:
an absolute path represent the real path of the file located by this object
Throws:
IOException - if the file does not exist or an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, its checkRead method is invoked to check read access to the file, and where this path is not absolute, its checkPropertyAccess method is invoked to check access to the system property user.dir

copyTo

public abstract Path copyTo(Path target,
                            CopyOption... options)
                     throws IOException
Copy the file located by this path to a target location.

This method copies the file located by this Path to the target location with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists, except if the source and target are the same file, in which case this method has no effect. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with the Files.walkFileTree utility method to copy a directory and all entries in the directory, or an entire file-tree where required.

The options parameter is an array of options and may contain any of the following:

Option Description
REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
COPY_ATTRIBUTES Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file store. Copying of file timestamps may result in precision loss.
NOFOLLOW_LINKS Symbolic links are not followed. If the file, located by this path, is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link.

An implementation of this interface may support additional implementation specific options.

Copying a file is not an atomic operation. If an IOException is thrown then it possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.

Parameters:
target - the target location
options - options specifying how the copy should be done
Returns:
the target
Throws:
UnsupportedOperationException - if the array contains a copy option that is not supported
FileAlreadyExistsException - if the target file exists and cannot be replaced because the REPLACE_EXISTING option is not specified, or the target file is a non-empty directory (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the source file, the checkWrite is invoked to check write access to the target file. If a symbolic link is copied the security manager is invoked to check LinkPermission("symbolic").

moveTo

public abstract Path moveTo(Path target,
                            CopyOption... options)
                     throws IOException
Move or rename the file located by this path to a target location.

By default, this method attempts to move the file to the target location, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException). To move a file tree may involve copying rather than moving directories and this can be done using the copyTo method in conjunction with the Files.walkFileTree utility method.

The options parameter is an array of options and may contain any of the following:

Option Description
REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
ATOMIC_MOVE The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException. If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a different FileStore and would require that the file be copied, or target location is associated with a different provider to this object.

An implementation of this interface may support additional implementation specific options.

Where the move requires that the file be copied then the last-modified-time is copied to the new file. An implementation may also attempt to copy other file attributes but is not required to fail if the file attributes cannot be copied. When the move is performed as a non-atomic operation, and a IOException is thrown, then the state of the files is not defined. The original file and the target file may both exist, the target file may be incomplete or some of its file attributes may not been copied from the original file.

Parameters:
target - the target location
options - options specifying how the move should be done
Returns:
the target
Throws:
UnsupportedOperationException - if the array contains a copy option that is not supported
FileAlreadyExistsException - if the target file exists and cannot be replaced because the REPLACE_EXISTING option is not specified, or the target file is a non-empty directory
AtomicMoveNotSupportedException - if the options array contains the ATOMIC_MOVE option but the file cannot be moved as an atomic file system operation.
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to both the source and target file.

newDirectoryStream

public abstract DirectoryStream<Path> newDirectoryStream()
                                                  throws IOException
Opens the directory referenced by this object, returning a DirectoryStream to iterate over all entries in the directory. The elements returned by the directory stream's iterator are of type Path, each one representing an entry in the directory. The Path objects are obtained as if by resolving the name of the directory entry against this path.

The directory stream's close method should be invoked after iteration is completed so as to free any resources held for the open directory.

When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is a SecureDirectoryStream.

Returns:
a new and open DirectoryStream object
Throws:
NotDirectoryException - if the file could not otherwise be opened because it is not a directory (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the directory.

newDirectoryStream

public abstract DirectoryStream<Path> newDirectoryStream(String glob)
                                                  throws IOException
Opens the directory referenced by this object, returning a DirectoryStream to iterate over the entries in the directory. The elements returned by the directory stream's iterator are of type Path, each one representing an entry in the directory. The Path objects are obtained as if by resolving the name of the directory entry against this path. The entries returned by the iterator are filtered by matching the String representation of their file names against the given globbing pattern.

For example, suppose we want to iterate over the files ending with ".java" in a directory:

     Path dir = ...
     DirectoryStream<Path> stream = dir.newDirectoryStream("*.java");
 

The globbing pattern is specified by the getPathMatcher method.

The directory stream's close method should be invoked after iteration is completed so as to free any resources held for the open directory.

When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is a SecureDirectoryStream.

Parameters:
glob - the glob pattern
Returns:
a new and open DirectoryStream object
Throws:
PatternSyntaxException - if the pattern is invalid
NotDirectoryException - if the file could not otherwise be opened because it is not a directory (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the directory.

newDirectoryStream

public abstract DirectoryStream<Path> newDirectoryStream(DirectoryStream.Filter<? super Path> filter)
                                                  throws IOException
Opens the directory referenced by this object, returning a DirectoryStream to iterate over the entries in the directory. The elements returned by the directory stream's iterator are of type Path, each one representing an entry in the directory. The Path objects are obtained as if by resolving the name of the directory entry against this path. The entries returned by the iterator are filtered by the given filter.

The directory stream's close method should be invoked after iteration is completed so as to free any resources held for the open directory.

Where the filter terminates due to an uncaught error or runtime exception then it is propagated to the hasNext or next method. Where an IOException is thrown, it results in the hasNext or next method throwing a DirectoryIteratorException with the IOException as the cause.

When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is a SecureDirectoryStream.

Usage Example: Suppose we want to iterate over the files in a directory that are larger than 8K.

     DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
         public boolean accept(Path file) throws IOException {
             long size = Attributes.readBasicFileAttributes(file).size();
             return (size > 8192L);
         }
     };
     Path dir = ...
     DirectoryStream<Path> stream = dir.newDirectoryStream(filter);
 

Parameters:
filter - the directory stream filter
Returns:
a new and open DirectoryStream object
Throws:
NotDirectoryException - if the file could not otherwise be opened because it is not a directory (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the directory.

createFile

public abstract Path createFile(FileAttribute<?>... attrs)
                         throws IOException
Creates a new and empty file, failing if the file already exists.

This Path locates the file to create. The check for the existence of the file and the creation of the new file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.

The attrs parameter is an optional array of file-attributes to set atomically when creating the file. Each attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

Parameters:
attrs - an optional list of file attributes to set atomically when creating the file
Returns:
this path
Throws:
UnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the file
FileAlreadyExistsException - if a file of that name already exists (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the new file.

createDirectory

public abstract Path createDirectory(FileAttribute<?>... attrs)
                              throws IOException
Creates a new directory.

This Path locates the directory to create. The check for the existence of the file and the creation of the directory if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.

The attrs parameter is an optional array of file-attributes to set atomically when creating the directory. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

Parameters:
attrs - an optional list of file attributes to set atomically when creating the directory
Returns:
this path
Throws:
UnsupportedOperationException - if the array contains an attribute that cannot be set atomically when creating the directory
FileAlreadyExistsException - if a directory could not otherwise be created because a file of that name already exists (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the new directory.
See Also:
Files.createDirectories(java.nio.file.Path, java.nio.file.attribute.FileAttribute<?>...)

newByteChannel

public abstract SeekableByteChannel newByteChannel(Set<? extends OpenOption> options,
                                                   FileAttribute<?>... attrs)
                                            throws IOException
Opens or creates a file, returning a seekable byte channel to access the file.

The options parameter determines how the file is opened. The READ and WRITE options determine if the file should be opened for reading and/or writing. If neither option (or the APPEND option) is contained in the array then the file is opened for reading. By default reading or writing commences at the beginning of the file.

In the addition to READ and WRITE, the following options may be present:

Option Description
APPEND If this option is present then the file is opened for writing and each invocation of the channel's write method first advances the position to the end of the file and then writes the requested data. Whether the advancement of the position and the writing of the data are done in a single atomic operation is system-dependent and therefore unspecified. This option may not be used in conjunction with the READ or TRUNCATE_EXISTING options.
TRUNCATE_EXISTING If this option is present then the existing file is truncated to a size of 0 bytes. This option is ignored when the file is opened only for reading.
CREATE_NEW If this option is present then a new file is created, failing if the file already exists or is a symbolic link. When creating a file the check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other file system operations. This option is ignored when the file is opened only for reading.
CREATE If this option is present then an existing file is opened if it exists, otherwise a new file is created. This option is ignored if the CREATE_NEW option is also present or the file is opened only for reading.
DELETE_ON_CLOSE When this option is present then the implementation makes a best effort attempt to delete the file when closed by the close method. If the close method is not invoked then a best effort attempt is made to delete the file when the Java virtual machine terminates.
SPARSE When creating a new file this option is a hint that the new file will be sparse. This option is ignored when not creating a new file.
SYNC Requires that every update to the file's content or metadata be written synchronously to the underlying storage device. (see Synchronized I/O file integrity).
DSYNC Requires that every update to the file's content be written synchronously to the underlying storage device. (see Synchronized I/O file integrity).

An implementation may also support additional implementation specific options.

The attrs parameter is an optional array of file file-attributes to set atomically when a new file is created.

In the case of the default provider, the returned seekable byte channel is a FileChannel.

Usage Examples:

     Path file = ...

     // open file for reading
     ReadableByteChannel rbc = file.newByteChannel(EnumSet.of(READ)));

     // open file for writing to the end of an existing file, creating
     // the file if it doesn't already exist
     WritableByteChannel wbc = file.newByteChannel(EnumSet.of(CREATE,APPEND));

     // create file with initial permissions, opening it for both reading and writing
     FileAttribute<Set<PosixFilePermission>> perms = ...
     SeekableByteChannel sbc = file.newByteChannel(EnumSet.of(CREATE_NEW,READ,WRITE), perms);
 

Parameters:
options - Options specifying how the file is opened
attrs - An optional list of file attributes to set atomically when creating the file
Returns:
a new seekable byte channel
Throws:
IllegalArgumentException - if the set contains an invalid combination of options
UnsupportedOperationException - if an unsupported open option is specified or the array contains attributes that cannot be set atomically when creating the file
FileAlreadyExistsException - if a file of that name already exists and the CREATE_NEW option is specified (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the path if the file is opened for reading. The checkWrite method is invoked to check write access to the path if the file is opened for writing.

newByteChannel

public abstract SeekableByteChannel newByteChannel(OpenOption... options)
                                            throws IOException
Opens or creates a file, returning a seekable byte channel to access the file.

This method opens or creates a file in exactly the manner specified by the newByteChannel method.

Parameters:
options - options specifying how the file is opened
Returns:
a new seekable byte channel
Throws:
IllegalArgumentException - if the set contains an invalid combination of options
UnsupportedOperationException - if an unsupported open option is specified
FileAlreadyExistsException - if a file of that name already exists and the CREATE_NEW option is specified (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the path if the file is opened for reading. The checkWrite method is invoked to check write access to the path if the file is opened for writing.

newOutputStream

public abstract OutputStream newOutputStream(OpenOption... options)
                                      throws IOException
Opens or creates the file located by this object for writing, returning an output stream to write bytes to the file.

This method opens or creates a file in exactly the manner specified by the newByteChannel method except that the READ option may not be present in the array of open options.

Specified by:
newOutputStream in interface FileRef
Parameters:
options - options specifying how the file is opened
Returns:
a new output stream
Throws:
IllegalArgumentException - if options contains an invalid combination of options
UnsupportedOperationException - if an unsupported option is specified
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the file.

isHidden

public abstract boolean isHidden()
                          throws IOException
Tells whether or not the file located by this object is considered hidden. The exact definition of hidden is platform or provider dependent. On UNIX for example a file is considered to be hidden if its name begins with a period character ('.'). On Windows a file is considered hidden if it isn't a directory and the DOS hidden attribute is set.

Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.

Returns:
true if the file is considered hidden
Throws:
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.

checkAccess

public abstract void checkAccess(AccessMode... modes)
                          throws IOException
Checks the existence and optionally the accessibility of the file located by this path.

This method checks the existence of a file and that this Java virtual machine has appropriate privileges that would allow it access the file according to all of access modes specified in the modes parameter as follows:

Value Description
READ Checks that the file exists and that the Java virtual machine has permission to read the file.
WRITE Checks that the file exists and that the Java virtual machine has permission to write to the file,
EXECUTE Checks that the file exists and that the Java virtual machine has permission to execute the file. The semantics may differ when checking access to a directory. For example, on UNIX systems, checking for EXECUTE access checks that the Java virtual machine has permission to search the directory in order to access file or subdirectories.

If the modes parameter is of length zero, then the existence of the file is checked.

This method follows symbolic links if the file referenced by this object is a symbolic link. Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. To determine the effective access to a file may require access to several attributes and so in some implementations this method may not be atomic with respect to other file system operations. Furthermore, as the result of this method is immediately outdated, there is no guarantee that a subsequence access will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

Parameters:
modes - The access modes to check; may have zero elements
Throws:
UnsupportedOperationException - an implementation is required to support checking for READ, WRITE, and EXECUTE access. This exception is specified to allow for the Access enum to be extended in future releases.
NoSuchFileException - if a file does not exist (optional specific exception)
AccessDeniedException - the requested access would be denied or the access cannot be determined because the Java virtual machine has insufficient privileges or other reasons. (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead is invoked when checking read access to the file or only the existence of the file, the checkWrite is invoked when checking write access to the file, and checkExec is invoked when checking execute access.

exists

public abstract boolean exists()
Tests whether the file located by this path exists.

This convenience method is intended for cases where it is required to take action when it can be confirmed that a file exists. This method simply invokes the checkAccess method to check if the file exists. If the checkAccess method succeeds then this method returns true, otherwise if an IOException is thrown (because the file doesn't exist or cannot be accessed by this Java virtual machine) then false is returned.

Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security sensitive applications.

Returns:
true if the file exists; false if the file does not exist or its existence cannot be determined.
Throws:
SecurityException - In the case of the default provider, the SecurityManager.checkRead(String) is invoked to check read access to the file.
See Also:
notExists()

notExists

public abstract boolean notExists()
Tests whether the file located by this path does not exist.

This convenience method is intended for cases where it is required to take action when it can be confirmed that a file does not exist. This method invokes the checkAccess method to check if the file exists. If the file does not exist then true is returned, otherwise the file exists or cannot be accessed by this Java virtual machine and false is returned.

Note that this method is not the complement of the exists method. Where it is not possible to determine if a file exists or not then both methods return false. As with the exists method, the result of this method is immediately outdated. If this method indicates the file does exist then there is no guarantee that a subsequence attempt to create the file will succeed. Care should be taken when using this method in security sensitive applications.

Returns:
true if the file does not exist; false if the file exists or its existence cannot be determined.
Throws:
SecurityException - In the case of the default provider, the SecurityManager.checkRead(String) is invoked to check read access to the file.

getFileStore

public abstract FileStore getFileStore()
                                throws IOException
Returns the FileStore representing the file store where an existing file, located by this path, is stored.

Once a reference to the FileStore is obtained it is implementation specific if operations on the returned FileStore, or FileStoreAttributeView objects obtained from it, continue to depend on the existence of the file. In particular the behavior is not defined for the case that the file is deleted or moved to a different file store.

Returns:
the file store where the file is stored
Throws:
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file, and in addition it checks RuntimePermission ("getFileStoreAttributes")

register

public abstract WatchKey register(WatchService watcher,
                                  WatchEvent.Kind<?>[] events,
                                  WatchEvent.Modifier... modifiers)
                           throws IOException
Registers the file located by this path with a watch service.

In this release, this path locates a directory that exists. The directory is registered with the watch service so that entries in the directory can be watched. The events parameter is an array of events to register and may contain the following events:

The context for these events is the relative path between the directory located by this path, and the path that locates the directory entry that is created, deleted, or modified.

The set of events may include additional implementation specific event that are not defined by the enum StandardWatchEventKind

The modifiers parameter is an array of modifiers that qualify how the directory is registered. This release does not define any standard modifiers. The array may contain implementation specific modifiers.

Where a file is registered with a watch service by means of a symbolic link then it is implementation specific if the watch continues to depend on the existence of the symbolic link after it is registered.

Specified by:
register in interface Watchable
Parameters:
watcher - the watch service to which this object is to be registered
events - the events for which this object should be registered
modifiers - the modifiers, if any, that modify how the object is registered
Returns:
a key representing the registration of this object with the given watch service
Throws:
UnsupportedOperationException - if unsupported events or modifiers are specified
IllegalArgumentException - if an invalid combination of events or modifiers is specified
ClosedWatchServiceException - if the watch service is closed
NotDirectoryException - if the file is registered to watch the entries in a directory and the file is not a directory (optional specific exception)
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.

register

public abstract WatchKey register(WatchService watcher,
                                  WatchEvent.Kind<?>... events)
                           throws IOException
Registers the file located by this path with a watch service.

An invocation of this method behaves in exactly the same way as the invocation

     watchable.register(watcher, events, new WatchEvent.Modifier[0]);
 

Usage Example: Suppose we wish to register a directory for entry create, delete, and modify events:

     Path dir = ...
     WatchService watcher = ...

     WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
 

Specified by:
register in interface Watchable
Parameters:
watcher - The watch service to which this object is to be registered
events - The events for which this object should be registered
Returns:
A key representing the registration of this object with the given watch service
Throws:
UnsupportedOperationException - If unsupported events are specified
IllegalArgumentException - If an invalid combination of events is specified
ClosedWatchServiceException - If the watch service is closed
NotDirectoryException - If the file is registered to watch the entries in a directory and the file is not a directory (optional specific exception)
IOException - If an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.

iterator

public abstract Iterator<Path> iterator()
Returns an iterator over the name elements of this path.

The first element returned by the iterator represents the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element returned is the name of the file or directory denoted by this path. The root component, if present, is not returned by the iterator.

Specified by:
iterator in interface Iterable<Path>
Returns:
an iterator over the name elements of this path.

compareTo

public abstract int compareTo(Path other)
Compares two abstract paths lexicographically. The ordering defined by this method is provider specific, and in the case of the default provider, platform specific. This method does not access the file system and neither file is required to exist.

Specified by:
compareTo in interface Comparable<Path>
Parameters:
other - the path compared to this path.
Returns:
zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument

isSameFile

public abstract boolean isSameFile(Path other)
                            throws IOException
Tests if the file referenced by this object is the same file referenced by another object.

If this Path and the given Path are equal then this method returns true without checking if the file exists. If the Path and the given Path are associated with different providers, or the given Path is null then this method returns false. Otherwise, this method checks if both Paths locate the same file, and depending on the implementation, may require to open or access both files.

If the file system and files remain static, then this method implements an equivalence relation for non-null Paths.

Parameters:
other - the other file reference
Returns:
true if, and only if, this object and the given object locate the same file
Throws:
IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to both files.
See Also:
BasicFileAttributes.fileKey()

equals

public abstract boolean equals(Object other)
Tests this path for equality with the given object.

If the given object is not a Path, or is a Path associated with a different provider, then this method immediately returns false.

Whether or not two path are equal depends on the file system implementation. In some cases the paths are compared without regard to case, and others are case sensitive. This method does not access the file system and the file is not required to exist.

This method satisfies the general contract of the Object.equals method.

Overrides:
equals in class Object
Parameters:
other - the object to which this object is to be compared
Returns:
true if, and only if, the given object is a Path that is identical to this Path
See Also:
Object.hashCode(), HashMap

hashCode

public abstract int hashCode()
Computes a hash code for this path.

The hash code is based upon the components of the path, and satisfies the general contract of the Object.hashCode method.

Overrides:
hashCode in class Object
Returns:
the hash-code value for this path
See Also:
Object.equals(java.lang.Object), System.identityHashCode(java.lang.Object)

toString

public abstract String toString()
Returns the string representation of this path.

If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path.

The returned path string uses the default name separator to separate names in the path.

Overrides:
toString in class Object
Returns:
the string representation of this path

Java™ Platform
Standard Ed. 7

DRAFT ea-b118

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.

Copyright © 1993, 2010, Oracle Corporation. All rights reserved.
DRAFT ea-b118

Scripting on this page tracks web page traffic, but does not change the content in any way.