Path: blob/master/src/java.base/share/classes/java/nio/file/Path.java
41159 views
/*1* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.file;2627import java.io.File;28import java.io.IOException;29import java.net.URI;30import java.nio.file.spi.FileSystemProvider;31import java.util.Iterator;32import java.util.NoSuchElementException;3334/**35* An object that may be used to locate a file in a file system. It will36* typically represent a system dependent file path.37*38* <p> A {@code Path} represents a path that is hierarchical and composed of a39* sequence of directory and file name elements separated by a special separator40* or delimiter. A <em>root component</em>, that identifies a file system41* hierarchy, may also be present. The name element that is <em>farthest</em>42* from the root of the directory hierarchy is the name of a file or directory.43* The other name elements are directory names. A {@code Path} can represent a44* root, a root and a sequence of names, or simply one or more name elements.45* A {@code Path} is considered to be an <i>empty path</i> if it consists46* solely of one name element that is empty. Accessing a file using an47* <i>empty path</i> is equivalent to accessing the default directory of the48* file system. {@code Path} defines the {@link #getFileName() getFileName},49* {@link #getParent getParent}, {@link #getRoot getRoot}, and {@link #subpath50* subpath} methods to access the path components or a subsequence of its name51* elements.52*53* <p> In addition to accessing the components of a path, a {@code Path} also54* defines the {@link #resolve(Path) resolve} and {@link #resolveSibling(Path)55* resolveSibling} methods to combine paths. The {@link #relativize relativize}56* method that can be used to construct a relative path between two paths.57* Paths can be {@link #compareTo compared}, and tested against each other using58* the {@link #startsWith startsWith} and {@link #endsWith endsWith} methods.59*60* <p> This interface extends {@link Watchable} interface so that a directory61* located by a path can be {@link #register registered} with a {@link62* WatchService} and entries in the directory watched. </p>63*64* <p> <b>WARNING:</b> This interface is only intended to be implemented by65* those developing custom file system implementations. Methods may be added to66* this interface in future releases. </p>67*68* <h2>Accessing Files</h2>69* <p> Paths may be used with the {@link Files} class to operate on files,70* directories, and other types of files. For example, suppose we want a {@link71* java.io.BufferedReader} to read text from a file "{@code access.log}". The72* file is located in a directory "{@code logs}" relative to the current working73* directory and is UTF-8 encoded.74* <pre>75* Path path = FileSystems.getDefault().getPath("logs", "access.log");76* BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);77* </pre>78*79* <a id="interop"></a><h2>Interoperability</h2>80* <p> Paths associated with the default {@link81* java.nio.file.spi.FileSystemProvider provider} are generally interoperable82* with the {@link java.io.File java.io.File} class. Paths created by other83* providers are unlikely to be interoperable with the abstract path names84* represented by {@code java.io.File}. The {@link java.io.File#toPath toPath}85* method may be used to obtain a {@code Path} from the abstract path name86* represented by a {@code java.io.File} object. The resulting {@code Path} can87* be used to operate on the same file as the {@code java.io.File} object. In88* addition, the {@link #toFile toFile} method is useful to construct a {@code89* File} from the {@code String} representation of a {@code Path}.90*91* <h2>Concurrency</h2>92* <p> Implementations of this interface are immutable and safe for use by93* multiple concurrent threads.94*95* @since 1.796*/9798public interface Path99extends Comparable<Path>, Iterable<Path>, Watchable100{101/**102* Returns a {@code Path} by converting a path string, or a sequence of103* strings that when joined form a path string. If {@code more} does not104* specify any elements then the value of the {@code first} parameter is105* the path string to convert. If {@code more} specifies one or more106* elements then each non-empty string, including {@code first}, is107* considered to be a sequence of name elements and is joined to form a108* path string. The details as to how the Strings are joined is provider109* specific but typically they will be joined using the110* {@link FileSystem#getSeparator name-separator} as the separator.111* For example, if the name separator is "{@code /}" and112* {@code getPath("/foo","bar","gus")} is invoked, then the path string113* {@code "/foo/bar/gus"} is converted to a {@code Path}. A {@code Path}114* representing an empty path is returned if {@code first} is the empty115* string and {@code more} does not contain any non-empty strings.116*117* <p> The {@code Path} is obtained by invoking the {@link FileSystem#getPath118* getPath} method of the {@link FileSystems#getDefault default} {@link119* FileSystem}.120*121* <p> Note that while this method is very convenient, using it will imply122* an assumed reference to the default {@code FileSystem} and limit the123* utility of the calling code. Hence it should not be used in library code124* intended for flexible reuse. A more flexible alternative is to use an125* existing {@code Path} instance as an anchor, such as:126* <pre>{@code127* Path dir = ...128* Path path = dir.resolve("file");129* }</pre>130*131* @param first132* the path string or initial part of the path string133* @param more134* additional strings to be joined to form the path string135*136* @return the resulting {@code Path}137*138* @throws InvalidPathException139* if the path string cannot be converted to a {@code Path}140*141* @see FileSystem#getPath142*143* @since 11144*/145public static Path of(String first, String... more) {146return FileSystems.getDefault().getPath(first, more);147}148149/**150* Returns a {@code Path} by converting a URI.151*152* <p> This method iterates over the {@link FileSystemProvider#installedProviders()153* installed} providers to locate the provider that is identified by the154* URI {@link URI#getScheme scheme} of the given URI. URI schemes are155* compared without regard to case. If the provider is found then its {@link156* FileSystemProvider#getPath getPath} method is invoked to convert the157* URI.158*159* <p> In the case of the default provider, identified by the URI scheme160* "file", the given URI has a non-empty path component, and undefined query161* and fragment components. Whether the authority component may be present162* is platform specific. The returned {@code Path} is associated with the163* {@link FileSystems#getDefault default} file system.164*165* <p> The default provider provides a similar <em>round-trip</em> guarantee166* to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it167* is guaranteed that168* <blockquote>{@code169* Path.of(}<i>p</i>{@code .}{@link Path#toUri() toUri}{@code ()).equals(}170* <i>p</i>{@code .}{@link Path#toAbsolutePath() toAbsolutePath}{@code ())}171* </blockquote>172* so long as the original {@code Path}, the {@code URI}, and the new {@code173* Path} are all created in (possibly different invocations of) the same174* Java virtual machine. Whether other providers make any guarantees is175* provider specific and therefore unspecified.176*177* @param uri178* the URI to convert179*180* @return the resulting {@code Path}181*182* @throws IllegalArgumentException183* if preconditions on the {@code uri} parameter do not hold. The184* format of the URI is provider specific.185* @throws FileSystemNotFoundException186* The file system, identified by the URI, does not exist and187* cannot be created automatically, or the provider identified by188* the URI's scheme component is not installed189* @throws SecurityException190* if a security manager is installed and it denies an unspecified191* permission to access the file system192*193* @since 11194*/195public static Path of(URI uri) {196String scheme = uri.getScheme();197if (scheme == null)198throw new IllegalArgumentException("Missing scheme");199200// check for default provider to avoid loading of installed providers201if (scheme.equalsIgnoreCase("file"))202return FileSystems.getDefault().provider().getPath(uri);203204// try to find provider205for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {206if (provider.getScheme().equalsIgnoreCase(scheme)) {207return provider.getPath(uri);208}209}210211throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed");212}213214/**215* Returns the file system that created this object.216*217* @return the file system that created this object218*/219FileSystem getFileSystem();220221/**222* Tells whether or not this path is absolute.223*224* <p> An absolute path is complete in that it doesn't need to be combined225* with other path information in order to locate a file.226*227* @return {@code true} if, and only if, this path is absolute228*/229boolean isAbsolute();230231/**232* Returns the root component of this path as a {@code Path} object,233* or {@code null} if this path does not have a root component.234*235* @return a path representing the root component of this path,236* or {@code null}237*/238Path getRoot();239240/**241* Returns the name of the file or directory denoted by this path as a242* {@code Path} object. The file name is the <em>farthest</em> element from243* the root in the directory hierarchy.244*245* @return a path representing the name of the file or directory, or246* {@code null} if this path has zero elements247*/248Path getFileName();249250/**251* Returns the <em>parent path</em>, or {@code null} if this path does not252* have a parent.253*254* <p> The parent of this path object consists of this path's root255* component, if any, and each element in the path except for the256* <em>farthest</em> from the root in the directory hierarchy. This method257* does not access the file system; the path or its parent may not exist.258* Furthermore, this method does not eliminate special names such as "."259* and ".." that may be used in some implementations. On UNIX for example,260* the parent of "{@code /a/b/c}" is "{@code /a/b}", and the parent of261* {@code "x/y/.}" is "{@code x/y}". This method may be used with the {@link262* #normalize normalize} method, to eliminate redundant names, for cases where263* <em>shell-like</em> navigation is required.264*265* <p> If this path has more than one element, and no root component, then266* this method is equivalent to evaluating the expression:267* <blockquote><pre>268* subpath(0, getNameCount()-1);269* </pre></blockquote>270*271* @return a path representing the path's parent272*/273Path getParent();274275/**276* Returns the number of name elements in the path.277*278* @return the number of elements in the path, or {@code 0} if this path279* only represents a root component280*/281int getNameCount();282283/**284* Returns a name element of this path as a {@code Path} object.285*286* <p> The {@code index} parameter is the index of the name element to return.287* The element that is <em>closest</em> to the root in the directory hierarchy288* has index {@code 0}. The element that is <em>farthest</em> from the root289* has index {@link #getNameCount count}{@code -1}.290*291* @param index292* the index of the element293*294* @return the name element295*296* @throws IllegalArgumentException297* if {@code index} is negative, {@code index} is greater than or298* equal to the number of elements, or this path has zero name299* elements300*/301Path getName(int index);302303/**304* Returns a relative {@code Path} that is a subsequence of the name305* elements of this path.306*307* <p> The {@code beginIndex} and {@code endIndex} parameters specify the308* subsequence of name elements. The name that is <em>closest</em> to the root309* in the directory hierarchy has index {@code 0}. The name that is310* <em>farthest</em> from the root has index {@link #getNameCount311* count}{@code -1}. The returned {@code Path} object has the name elements312* that begin at {@code beginIndex} and extend to the element at index {@code313* endIndex-1}.314*315* @param beginIndex316* the index of the first element, inclusive317* @param endIndex318* the index of the last element, exclusive319*320* @return a new {@code Path} object that is a subsequence of the name321* elements in this {@code Path}322*323* @throws IllegalArgumentException324* if {@code beginIndex} is negative, or greater than or equal to325* the number of elements. If {@code endIndex} is less than or326* equal to {@code beginIndex}, or larger than the number of elements.327*/328Path subpath(int beginIndex, int endIndex);329330/**331* Tests if this path starts with the given path.332*333* <p> This path <em>starts</em> with the given path if this path's root334* component <em>starts</em> with the root component of the given path,335* and this path starts with the same name elements as the given path.336* If the given path has more name elements than this path then {@code false}337* is returned.338*339* <p> Whether or not the root component of this path starts with the root340* component of the given path is file system specific. If this path does341* not have a root component and the given path has a root component then342* this path does not start with the given path.343*344* <p> If the given path is associated with a different {@code FileSystem}345* to this path then {@code false} is returned.346*347* @param other348* the given path349*350* @return {@code true} if this path starts with the given path; otherwise351* {@code false}352*/353boolean startsWith(Path other);354355/**356* Tests if this path starts with a {@code Path}, constructed by converting357* the given path string, in exactly the manner specified by the {@link358* #startsWith(Path) startsWith(Path)} method. On UNIX for example, the path359* "{@code foo/bar}" starts with "{@code foo}" and "{@code foo/bar}". It360* does not start with "{@code f}" or "{@code fo}".361*362* @implSpec363* The default implementation is equivalent for this path to:364* <pre>{@code365* startsWith(getFileSystem().getPath(other));366* }</pre>367*368* @param other369* the given path string370*371* @return {@code true} if this path starts with the given path; otherwise372* {@code false}373*374* @throws InvalidPathException375* If the path string cannot be converted to a Path.376*/377default boolean startsWith(String other) {378return startsWith(getFileSystem().getPath(other));379}380381/**382* Tests if this path ends with the given path.383*384* <p> If the given path has <em>N</em> elements, and no root component,385* and this path has <em>N</em> or more elements, then this path ends with386* the given path if the last <em>N</em> elements of each path, starting at387* the element farthest from the root, are equal.388*389* <p> If the given path has a root component then this path ends with the390* given path if the root component of this path <em>ends with</em> the root391* component of the given path, and the corresponding elements of both paths392* are equal. Whether or not the root component of this path ends with the393* root component of the given path is file system specific. If this path394* does not have a root component and the given path has a root component395* then this path does not end with the given path.396*397* <p> If the given path is associated with a different {@code FileSystem}398* to this path then {@code false} is returned.399*400* @param other401* the given path402*403* @return {@code true} if this path ends with the given path; otherwise404* {@code false}405*/406boolean endsWith(Path other);407408/**409* Tests if this path ends with a {@code Path}, constructed by converting410* the given path string, in exactly the manner specified by the {@link411* #endsWith(Path) endsWith(Path)} method. On UNIX for example, the path412* "{@code foo/bar}" ends with "{@code foo/bar}" and "{@code bar}". It does413* not end with "{@code r}" or "{@code /bar}". Note that trailing separators414* are not taken into account, and so invoking this method on the {@code415* Path}"{@code foo/bar}" with the {@code String} "{@code bar/}" returns416* {@code true}.417*418* @implSpec419* The default implementation is equivalent for this path to:420* <pre>{@code421* endsWith(getFileSystem().getPath(other));422* }</pre>423*424* @param other425* the given path string426*427* @return {@code true} if this path ends with the given path; otherwise428* {@code false}429*430* @throws InvalidPathException431* If the path string cannot be converted to a Path.432*/433default boolean endsWith(String other) {434return endsWith(getFileSystem().getPath(other));435}436437/**438* Returns a path that is this path with redundant name elements eliminated.439*440* <p> The precise definition of this method is implementation dependent but441* in general it derives from this path, a path that does not contain442* <em>redundant</em> name elements. In many file systems, the "{@code .}"443* and "{@code ..}" are special names used to indicate the current directory444* and parent directory. In such file systems all occurrences of "{@code .}"445* are considered redundant. If a "{@code ..}" is preceded by a446* non-"{@code ..}" name then both names are considered redundant (the447* process to identify such names is repeated until it is no longer448* applicable).449*450* <p> This method does not access the file system; the path may not locate451* a file that exists. Eliminating "{@code ..}" and a preceding name from a452* path may result in the path that locates a different file than the original453* path. This can arise when the preceding name is a symbolic link.454*455* @return the resulting path or this path if it does not contain456* redundant name elements; an empty path is returned if this path457* does not have a root component and all name elements are redundant458*459* @see #getParent460* @see #toRealPath461*/462Path normalize();463464// -- resolution and relativization --465466/**467* Resolve the given path against this path.468*469* <p> If the {@code other} parameter is an {@link #isAbsolute() absolute}470* path then this method trivially returns {@code other}. If {@code other}471* is an <i>empty path</i> then this method trivially returns this path.472* Otherwise this method considers this path to be a directory and resolves473* the given path against this path. In the simplest case, the given path474* does not have a {@link #getRoot root} component, in which case this method475* <em>joins</em> the given path to this path and returns a resulting path476* that {@link #endsWith ends} with the given path. Where the given path has477* a root component then resolution is highly implementation dependent and478* therefore unspecified.479*480* @param other481* the path to resolve against this path482*483* @return the resulting path484*485* @see #relativize486*/487Path resolve(Path other);488489/**490* Converts a given path string to a {@code Path} and resolves it against491* this {@code Path} in exactly the manner specified by the {@link492* #resolve(Path) resolve} method. For example, suppose that the name493* separator is "{@code /}" and a path represents "{@code foo/bar}", then494* invoking this method with the path string "{@code gus}" will result in495* the {@code Path} "{@code foo/bar/gus}".496*497* @implSpec498* The default implementation is equivalent for this path to:499* <pre>{@code500* resolve(getFileSystem().getPath(other));501* }</pre>502*503* @param other504* the path string to resolve against this path505*506* @return the resulting path507*508* @throws InvalidPathException509* if the path string cannot be converted to a Path.510*511* @see FileSystem#getPath512*/513default Path resolve(String other) {514return resolve(getFileSystem().getPath(other));515}516517/**518* Resolves the given path against this path's {@link #getParent parent}519* path. This is useful where a file name needs to be <i>replaced</i> with520* another file name. For example, suppose that the name separator is521* "{@code /}" and a path represents "{@code dir1/dir2/foo}", then invoking522* this method with the {@code Path} "{@code bar}" will result in the {@code523* Path} "{@code dir1/dir2/bar}". If this path does not have a parent path,524* or {@code other} is {@link #isAbsolute() absolute}, then this method525* returns {@code other}. If {@code other} is an empty path then this method526* returns this path's parent, or where this path doesn't have a parent, the527* empty path.528*529* @implSpec530* The default implementation is equivalent for this path to:531* <pre>{@code532* (getParent() == null) ? other : getParent().resolve(other);533* }</pre>534* unless {@code other == null}, in which case a535* {@code NullPointerException} is thrown.536*537* @param other538* the path to resolve against this path's parent539*540* @return the resulting path541*542* @see #resolve(Path)543*/544default Path resolveSibling(Path other) {545if (other == null)546throw new NullPointerException();547Path parent = getParent();548return (parent == null) ? other : parent.resolve(other);549}550551/**552* Converts a given path string to a {@code Path} and resolves it against553* this path's {@link #getParent parent} path in exactly the manner554* specified by the {@link #resolveSibling(Path) resolveSibling} method.555*556* @implSpec557* The default implementation is equivalent for this path to:558* <pre>{@code559* resolveSibling(getFileSystem().getPath(other));560* }</pre>561*562* @param other563* the path string to resolve against this path's parent564*565* @return the resulting path566*567* @throws InvalidPathException568* if the path string cannot be converted to a Path.569*570* @see FileSystem#getPath571*/572default Path resolveSibling(String other) {573return resolveSibling(getFileSystem().getPath(other));574}575576/**577* Constructs a relative path between this path and a given path.578*579* <p> Relativization is the inverse of {@link #resolve(Path) resolution}.580* This method attempts to construct a {@link #isAbsolute relative} path581* that when {@link #resolve(Path) resolved} against this path, yields a582* path that locates the same file as the given path. For example, on UNIX,583* if this path is {@code "/a/b"} and the given path is {@code "/a/b/c/d"}584* then the resulting relative path would be {@code "c/d"}. Where this585* path and the given path do not have a {@link #getRoot root} component,586* then a relative path can be constructed. A relative path cannot be587* constructed if only one of the paths have a root component. Where both588* paths have a root component then it is implementation dependent if a589* relative path can be constructed. If this path and the given path are590* {@link #equals equal} then an <i>empty path</i> is returned.591*592* <p> For any two {@link #normalize normalized} paths <i>p</i> and593* <i>q</i>, where <i>q</i> does not have a root component,594* <blockquote>595* <i>p</i>{@code .relativize(}<i>p</i>596* {@code .resolve(}<i>q</i>{@code )).equals(}<i>q</i>{@code )}597* </blockquote>598*599* <p> When symbolic links are supported, then whether the resulting path,600* when resolved against this path, yields a path that can be used to locate601* the {@link Files#isSameFile same} file as {@code other} is implementation602* dependent. For example, if this path is {@code "/a/b"} and the given603* path is {@code "/a/x"} then the resulting relative path may be {@code604* "../x"}. If {@code "b"} is a symbolic link then is implementation605* dependent if {@code "a/b/../x"} would locate the same file as {@code "/a/x"}.606*607* @param other608* the path to relativize against this path609*610* @return the resulting relative path, or an empty path if both paths are611* equal612*613* @throws IllegalArgumentException614* if {@code other} is not a {@code Path} that can be relativized615* against this path616*/617Path relativize(Path other);618619/**620* Returns a URI to represent this path.621*622* <p> This method constructs an absolute {@link URI} with a {@link623* URI#getScheme() scheme} equal to the URI scheme that identifies the624* provider. The exact form of the scheme specific part is highly provider625* dependent.626*627* <p> In the case of the default provider, the URI is hierarchical with628* a {@link URI#getPath() path} component that is absolute. The query and629* fragment components are undefined. Whether the authority component is630* defined or not is implementation dependent. There is no guarantee that631* the {@code URI} may be used to construct a {@link java.io.File java.io.File}.632* In particular, if this path represents a Universal Naming Convention (UNC)633* path, then the UNC server name may be encoded in the authority component634* of the resulting URI. In the case of the default provider, and the file635* exists, and it can be determined that the file is a directory, then the636* resulting {@code URI} will end with a slash.637*638* <p> The default provider provides a similar <em>round-trip</em> guarantee639* to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it640* is guaranteed that641* <blockquote>642* {@link Path#of(URI) Path.of}{@code (}<i>p</i>{@code .toUri()).equals(}<i>p</i>643* {@code .}{@link #toAbsolutePath() toAbsolutePath}{@code ())}644* </blockquote>645* so long as the original {@code Path}, the {@code URI}, and the new {@code646* Path} are all created in (possibly different invocations of) the same647* Java virtual machine. Whether other providers make any guarantees is648* provider specific and therefore unspecified.649*650* <p> When a file system is constructed to access the contents of a file651* as a file system then it is highly implementation specific if the returned652* URI represents the given path in the file system or it represents a653* <em>compound</em> URI that encodes the URI of the enclosing file system.654* A format for compound URIs is not defined in this release; such a scheme655* may be added in a future release.656*657* @return the URI representing this path658*659* @throws java.io.IOError660* if an I/O error occurs obtaining the absolute path, or where a661* file system is constructed to access the contents of a file as662* a file system, and the URI of the enclosing file system cannot be663* obtained664*665* @throws SecurityException666* In the case of the default provider, and a security manager667* is installed, the {@link #toAbsolutePath toAbsolutePath} method668* throws a security exception.669*/670URI toUri();671672/**673* Returns a {@code Path} object representing the absolute path of this674* path.675*676* <p> If this path is already {@link Path#isAbsolute absolute} then this677* method simply returns this path. Otherwise, this method resolves the path678* in an implementation dependent manner, typically by resolving the path679* against a file system default directory. Depending on the implementation,680* this method may throw an I/O error if the file system is not accessible.681*682* @return a {@code Path} object representing the absolute path683*684* @throws java.io.IOError685* if an I/O error occurs686* @throws SecurityException687* In the case of the default provider, a security manager688* is installed, and this path is not absolute, then the security689* manager's {@link SecurityManager#checkPropertyAccess(String)690* checkPropertyAccess} method is invoked to check access to the691* system property {@code user.dir}692*/693Path toAbsolutePath();694695/**696* Returns the <em>real</em> path of an existing file.697*698* <p> The precise definition of this method is implementation dependent but699* in general it derives from this path, an {@link #isAbsolute absolute}700* path that locates the {@link Files#isSameFile same} file as this path, but701* with name elements that represent the actual name of the directories702* and the file. For example, where filename comparisons on a file system703* are case insensitive then the name elements represent the names in their704* actual case. Additionally, the resulting path has redundant name705* elements removed.706*707* <p> If this path is relative then its absolute path is first obtained,708* as if by invoking the {@link #toAbsolutePath toAbsolutePath} method.709*710* <p> The {@code options} array may be used to indicate how symbolic links711* are handled. By default, symbolic links are resolved to their final712* target. If the option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is713* present then this method does not resolve symbolic links.714*715* Some implementations allow special names such as "{@code ..}" to refer to716* the parent directory. When deriving the <em>real path</em>, and a717* "{@code ..}" (or equivalent) is preceded by a non-"{@code ..}" name then718* an implementation will typically cause both names to be removed. When719* not resolving symbolic links and the preceding name is a symbolic link720* then the names are only removed if it guaranteed that the resulting path721* will locate the same file as this path.722*723* @param options724* options indicating how symbolic links are handled725*726* @return an absolute path represent the <em>real</em> path of the file727* located by this object728*729* @throws IOException730* if the file does not exist or an I/O error occurs731* @throws SecurityException732* In the case of the default provider, and a security manager733* is installed, its {@link SecurityManager#checkRead(String) checkRead}734* method is invoked to check read access to the file, and where735* this path is not absolute, its {@link SecurityManager#checkPropertyAccess(String)736* checkPropertyAccess} method is invoked to check access to the737* system property {@code user.dir}738*/739Path toRealPath(LinkOption... options) throws IOException;740741/**742* Returns a {@link File} object representing this path. Where this {@code743* Path} is associated with the default provider, then this method is744* equivalent to returning a {@code File} object constructed with the745* {@code String} representation of this path.746*747* <p> If this path was created by invoking the {@code File} {@link748* File#toPath toPath} method then there is no guarantee that the {@code749* File} object returned by this method is {@link #equals equal} to the750* original {@code File}.751*752* @implSpec753* The default implementation is equivalent for this path to:754* <pre>{@code755* new File(toString());756* }</pre>757* if the {@code FileSystem} which created this {@code Path} is the default758* file system; otherwise an {@code UnsupportedOperationException} is759* thrown.760*761* @return a {@code File} object representing this path762*763* @throws UnsupportedOperationException764* if this {@code Path} is not associated with the default provider765*/766default File toFile() {767if (getFileSystem() == FileSystems.getDefault()) {768return new File(toString());769} else {770throw new UnsupportedOperationException("Path not associated with "771+ "default file system.");772}773}774775// -- watchable --776777/**778* Registers the file located by this path with a watch service.779*780* <p> In this release, this path locates a directory that exists. The781* directory is registered with the watch service so that entries in the782* directory can be watched. The {@code events} parameter is the events to783* register and may contain the following events:784* <ul>785* <li>{@link StandardWatchEventKinds#ENTRY_CREATE ENTRY_CREATE} -786* entry created or moved into the directory</li>787* <li>{@link StandardWatchEventKinds#ENTRY_DELETE ENTRY_DELETE} -788* entry deleted or moved out of the directory</li>789* <li>{@link StandardWatchEventKinds#ENTRY_MODIFY ENTRY_MODIFY} -790* entry in directory was modified</li>791* </ul>792*793* <p> The {@link WatchEvent#context context} for these events is the794* relative path between the directory located by this path, and the path795* that locates the directory entry that is created, deleted, or modified.796*797* <p> The set of events may include additional implementation specific798* event that are not defined by the enum {@link StandardWatchEventKinds}799*800* <p> The {@code modifiers} parameter specifies <em>modifiers</em> that801* qualify how the directory is registered. This release does not define any802* <em>standard</em> modifiers. It may contain implementation specific803* modifiers.804*805* <p> Where a file is registered with a watch service by means of a symbolic806* link then it is implementation specific if the watch continues to depend807* on the existence of the symbolic link after it is registered.808*809* @param watcher810* the watch service to which this object is to be registered811* @param events812* the events for which this object should be registered813* @param modifiers814* the modifiers, if any, that modify how the object is registered815*816* @return a key representing the registration of this object with the817* given watch service818*819* @throws UnsupportedOperationException820* if unsupported events or modifiers are specified821* @throws IllegalArgumentException822* if an invalid combination of events or modifiers is specified823* @throws ClosedWatchServiceException824* if the watch service is closed825* @throws NotDirectoryException826* if the file is registered to watch the entries in a directory827* and the file is not a directory <i>(optional specific exception)</i>828* @throws IOException829* if an I/O error occurs830* @throws SecurityException831* In the case of the default provider, and a security manager is832* installed, the {@link SecurityManager#checkRead(String) checkRead}833* method is invoked to check read access to the file.834*/835@Override836WatchKey register(WatchService watcher,837WatchEvent.Kind<?>[] events,838WatchEvent.Modifier... modifiers)839throws IOException;840841/**842* Registers the file located by this path with a watch service.843*844* <p> An invocation of this method behaves in exactly the same way as the845* invocation846* <pre>847* watchable.{@link #register(WatchService,WatchEvent.Kind[],WatchEvent.Modifier[]) register}(watcher, events, new WatchEvent.Modifier[0]);848* </pre>849*850* <p> <b>Usage Example:</b>851* Suppose we wish to register a directory for entry create, delete, and modify852* events:853* <pre>854* Path dir = ...855* WatchService watcher = ...856*857* WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);858* </pre>859*860* @implSpec861* The default implementation is equivalent for this path to:862* <pre>{@code863* register(watcher, events, new WatchEvent.Modifier[0]);864* }</pre>865*866* @param watcher867* The watch service to which this object is to be registered868* @param events869* The events for which this object should be registered870*871* @return A key representing the registration of this object with the872* given watch service873*874* @throws UnsupportedOperationException875* If unsupported events are specified876* @throws IllegalArgumentException877* If an invalid combination of events is specified878* @throws ClosedWatchServiceException879* If the watch service is closed880* @throws NotDirectoryException881* If the file is registered to watch the entries in a directory882* and the file is not a directory <i>(optional specific exception)</i>883* @throws IOException884* If an I/O error occurs885* @throws SecurityException886* In the case of the default provider, and a security manager is887* installed, the {@link SecurityManager#checkRead(String) checkRead}888* method is invoked to check read access to the file.889*/890@Override891default WatchKey register(WatchService watcher,892WatchEvent.Kind<?>... events) throws IOException {893return register(watcher, events, new WatchEvent.Modifier[0]);894}895896// -- Iterable --897898/**899* Returns an iterator over the name elements of this path.900*901* <p> The first element returned by the iterator represents the name902* element that is closest to the root in the directory hierarchy, the903* second element is the next closest, and so on. The last element returned904* is the name of the file or directory denoted by this path. The {@link905* #getRoot root} component, if present, is not returned by the iterator.906*907* @implSpec908* The default implementation returns an {@code Iterator<Path>} which, for909* this path, traverses the {@code Path}s returned by910* {@code getName(index)}, where {@code index} ranges from zero to911* {@code getNameCount() - 1}, inclusive.912*913* @return an iterator over the name elements of this path.914*/915@Override916default Iterator<Path> iterator() {917return new Iterator<>() {918private int i = 0;919920@Override921public boolean hasNext() {922return (i < getNameCount());923}924925@Override926public Path next() {927if (i < getNameCount()) {928Path result = getName(i);929i++;930return result;931} else {932throw new NoSuchElementException();933}934}935};936}937938// -- compareTo/equals/hashCode --939940/**941* Compares two abstract paths lexicographically. The ordering defined by942* this method is provider specific, and in the case of the default943* provider, platform specific. This method does not access the file system944* and neither file is required to exist.945*946* <p> This method may not be used to compare paths that are associated947* with different file system providers.948*949* @param other the path compared to this path.950*951* @return zero if the argument is {@link #equals equal} to this path, a952* value less than zero if this path is lexicographically less than953* the argument, or a value greater than zero if this path is954* lexicographically greater than the argument955*956* @throws ClassCastException957* if the paths are associated with different providers958*/959@Override960int compareTo(Path other);961962/**963* Tests this path for equality with the given object.964*965* <p> If the given object is not a Path, or is a Path associated with a966* different {@code FileSystem}, then this method returns {@code false}.967*968* <p> Whether or not two path are equal depends on the file system969* implementation. In some cases the paths are compared without regard970* to case, and others are case sensitive. This method does not access the971* file system and the file is not required to exist. Where required, the972* {@link Files#isSameFile isSameFile} method may be used to check if two973* paths locate the same file.974*975* <p> This method satisfies the general contract of the {@link976* java.lang.Object#equals(Object) Object.equals} method. </p>977*978* @param other979* the object to which this object is to be compared980*981* @return {@code true} if, and only if, the given object is a {@code Path}982* that is identical to this {@code Path}983*/984boolean equals(Object other);985986/**987* Computes a hash code for this path.988*989* <p> The hash code is based upon the components of the path, and990* satisfies the general contract of the {@link Object#hashCode991* Object.hashCode} method.992*993* @return the hash-code value for this path994*/995int hashCode();996997/**998* Returns the string representation of this path.999*1000* <p> If this path was created by converting a path string using the1001* {@link FileSystem#getPath getPath} method then the path string returned1002* by this method may differ from the original String used to create the path.1003*1004* <p> The returned path string uses the default name {@link1005* FileSystem#getSeparator separator} to separate names in the path.1006*1007* @return the string representation of this path1008*/1009String toString();1010}101110121013