1 /* 2 * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.nio.file; 27 28 import java.io.File; 29 import java.io.IOException; 30 import java.net.URI; 31 import java.nio.file.spi.FileSystemProvider; 32 import java.util.Iterator; 33 import java.util.NoSuchElementException; 34 35 /** 36 * An object that may be used to locate a file in a file system. It will 37 * typically represent a system dependent file path. 38 * 39 * <p> A {@code Path} represents a path that is hierarchical and composed of a 40 * sequence of directory and file name elements separated by a special separator 41 * or delimiter. A <em>root component</em>, that identifies a file system 42 * hierarchy, may also be present. The name element that is <em>farthest</em> 43 * from the root of the directory hierarchy is the name of a file or directory. 44 * The other name elements are directory names. A {@code Path} can represent a 45 * root, a root and a sequence of names, or simply one or more name elements. 46 * A {@code Path} is considered to be an <i>empty path</i> if it consists 47 * solely of one name element that is empty. Accessing a file using an 48 * <i>empty path</i> is equivalent to accessing the default directory of the 49 * file system. {@code Path} defines the {@link #getFileName() getFileName}, 50 * {@link #getParent getParent}, {@link #getRoot getRoot}, and {@link #subpath 51 * subpath} methods to access the path components or a subsequence of its name 52 * elements. 53 * 54 * <p> In addition to accessing the components of a path, a {@code Path} also 55 * defines the {@link #resolve(Path) resolve} and {@link #resolveSibling(Path) 56 * resolveSibling} methods to combine paths. The {@link #relativize relativize} 57 * method that can be used to construct a relative path between two paths. 58 * Paths can be {@link #compareTo compared}, and tested against each other using 59 * the {@link #startsWith startsWith} and {@link #endsWith endsWith} methods. 60 * 61 * <p> This interface extends {@link Watchable} interface so that a directory 62 * located by a path can be {@link #register registered} with a {@link 63 * WatchService} and entries in the directory watched. </p> 64 * 65 * <p> <b>WARNING:</b> This interface is only intended to be implemented by 66 * those developing custom file system implementations. Methods may be added to 67 * this interface in future releases. </p> 68 * 69 * <h2>Accessing Files</h2> 70 * <p> Paths may be used with the {@link Files} class to operate on files, 71 * directories, and other types of files. For example, suppose we want a {@link 72 * java.io.BufferedReader} to read text from a file "{@code access.log}". The 73 * file is located in a directory "{@code logs}" relative to the current working 74 * directory and is UTF-8 encoded. 75 * <pre> 76 * Path path = FileSystems.getDefault().getPath("logs", "access.log"); 77 * BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); 78 * </pre> 79 * 80 * <a id="interop"></a><h2>Interoperability</h2> 81 * <p> Paths associated with the default {@link 82 * java.nio.file.spi.FileSystemProvider provider} are generally interoperable 83 * with the {@link java.io.File java.io.File} class. Paths created by other 84 * providers are unlikely to be interoperable with the abstract path names 85 * represented by {@code java.io.File}. The {@link java.io.File#toPath toPath} 86 * method may be used to obtain a {@code Path} from the abstract path name 87 * represented by a {@code java.io.File} object. The resulting {@code Path} can 88 * be used to operate on the same file as the {@code java.io.File} object. In 89 * addition, the {@link #toFile toFile} method is useful to construct a {@code 90 * File} from the {@code String} representation of a {@code Path}. 91 * 92 * <h2>Concurrency</h2> 93 * <p> Implementations of this interface are immutable and safe for use by 94 * multiple concurrent threads. 95 * 96 * @since 1.7 97 */ 98 99 public interface Path 100 extends Comparable<Path>, Iterable<Path>, Watchable 101 { 102 /** 103 * Converts a path string, or a sequence of strings that when joined form 104 * a path string, to a {@code Path}. If {@code more} does not specify any 105 * elements then the value of the {@code first} parameter is the path string 106 * to convert. If {@code more} specifies one or more elements then each 107 * non-empty string, including {@code first}, is considered to be a sequence 108 * of name elements and is joined to form a path string. 109 * The details as to how the Strings are joined is provider specific but 110 * typically they will be joined using the {@link FileSystem#getSeparator 111 * name-separator} as the separator. For example, if the name separator is 112 * "{@code /}" and {@code getPath("/foo","bar","gus")} is invoked, then the 113 * path string {@code "/foo/bar/gus"} is converted to a {@code Path}. 114 * A {@code Path} representing an empty path is returned if {@code first} 115 * is the empty string and {@code more} does not contain any non-empty 116 * strings. 117 * 118 * <p> The {@code Path} is obtained by invoking the {@link FileSystem#getPath 119 * getPath} method of the {@link FileSystems#getDefault default} {@link 120 * FileSystem}. 121 * 122 * <p> Note that while this method is very convenient, using it will imply 123 * an assumed reference to the default {@code FileSystem} and limit the 124 * utility of the calling code. Hence it should not be used in library code 125 * intended for flexible reuse. A more flexible alternative is to use an 126 * existing {@code Path} instance as an anchor, such as: 127 * <pre> 128 * Path dir = ... 129 * Path path = dir.resolve("file"); 130 * </pre> 131 * 132 * @param first 133 * the path string or initial part of the path string 134 * @param more 135 * additional strings to be joined to form the path string 136 * 137 * @return the resulting {@code Path} 138 * 139 * @throws InvalidPathException 140 * if the path string cannot be converted to a {@code Path} 141 * 142 * @see FileSystem#getPath 143 */ 144 public static Path get(String first, String... more) { 145 return FileSystems.getDefault().getPath(first, more); 146 } 147 148 /** 149 * Converts the given URI to a {@link Path} object. 150 * 151 * <p> This method iterates over the {@link FileSystemProvider#installedProviders() 152 * installed} providers to locate the provider that is identified by the 153 * URI {@link URI#getScheme scheme} of the given URI. URI schemes are 154 * compared without regard to case. If the provider is found then its {@link 155 * FileSystemProvider#getPath getPath} method is invoked to convert the 156 * URI. 157 * 158 * <p> In the case of the default provider, identified by the URI scheme 159 * "file", the given URI has a non-empty path component, and undefined query 160 * and fragment components. Whether the authority component may be present 161 * is platform specific. The returned {@code Path} is associated with the 162 * {@link FileSystems#getDefault default} file system. 163 * 164 * <p> The default provider provides a similar <em>round-trip</em> guarantee 165 * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it 166 * is guaranteed that 167 * <blockquote>{@code 168 * Path.get(}<i>p</i>{@code .}{@link Path#toUri() toUri}{@code ()).equals(} 169 * <i>p</i>{@code .}{@link Path#toAbsolutePath() toAbsolutePath}{@code ())} 170 * </blockquote> 171 * so long as the original {@code Path}, the {@code URI}, and the new {@code 172 * Path} are all created in (possibly different invocations of) the same 173 * Java virtual machine. Whether other providers make any guarantees is 174 * provider specific and therefore unspecified. 175 * 176 * @param uri 177 * the URI to convert 178 * 179 * @return the resulting {@code Path} 180 * 181 * @throws IllegalArgumentException 182 * if preconditions on the {@code uri} parameter do not hold. The 183 * format of the URI is provider specific. 184 * @throws FileSystemNotFoundException 185 * The file system, identified by the URI, does not exist and 186 * cannot be created automatically, or the provider identified by 187 * the URI's scheme component is not installed 188 * @throws SecurityException 189 * if a security manager is installed and it denies an unspecified 190 * permission to access the file system 191 */ 192 public static Path get(URI uri) { 193 String scheme = uri.getScheme(); 194 if (scheme == null) 195 throw new IllegalArgumentException("Missing scheme"); 196 197 // check for default provider to avoid loading of installed providers 198 if (scheme.equalsIgnoreCase("file")) 199 return FileSystems.getDefault().provider().getPath(uri); 200 201 // try to find provider 202 for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { 203 if (provider.getScheme().equalsIgnoreCase(scheme)) { 204 return provider.getPath(uri); 205 } 206 } 207 208 throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed"); 209 } 210 211 /** 212 * Returns the file system that created this object. 213 * 214 * @return the file system that created this object 215 */ 216 FileSystem getFileSystem(); 217 218 /** 219 * Tells whether or not this path is absolute. 220 * 221 * <p> An absolute path is complete in that it doesn't need to be combined 222 * with other path information in order to locate a file. 223 * 224 * @return {@code true} if, and only if, this path is absolute 225 */ 226 boolean isAbsolute(); 227 228 /** 229 * Returns the root component of this path as a {@code Path} object, 230 * or {@code null} if this path does not have a root component. 231 * 232 * @return a path representing the root component of this path, 233 * or {@code null} 234 */ 235 Path getRoot(); 236 237 /** 238 * Returns the name of the file or directory denoted by this path as a 239 * {@code Path} object. The file name is the <em>farthest</em> element from 240 * the root in the directory hierarchy. 241 * 242 * @return a path representing the name of the file or directory, or 243 * {@code null} if this path has zero elements 244 */ 245 Path getFileName(); 246 247 /** 248 * Returns the <em>parent path</em>, or {@code null} if this path does not 249 * have a parent. 250 * 251 * <p> The parent of this path object consists of this path's root 252 * component, if any, and each element in the path except for the 253 * <em>farthest</em> from the root in the directory hierarchy. This method 254 * does not access the file system; the path or its parent may not exist. 255 * Furthermore, this method does not eliminate special names such as "." 256 * and ".." that may be used in some implementations. On UNIX for example, 257 * the parent of "{@code /a/b/c}" is "{@code /a/b}", and the parent of 258 * {@code "x/y/.}" is "{@code x/y}". This method may be used with the {@link 259 * #normalize normalize} method, to eliminate redundant names, for cases where 260 * <em>shell-like</em> navigation is required. 261 * 262 * <p> If this path has more than one element, and no root component, then 263 * this method is equivalent to evaluating the expression: 264 * <blockquote><pre> 265 * subpath(0, getNameCount()-1); 266 * </pre></blockquote> 267 * 268 * @return a path representing the path's parent 269 */ 270 Path getParent(); 271 272 /** 273 * Returns the number of name elements in the path. 274 * 275 * @return the number of elements in the path, or {@code 0} if this path 276 * only represents a root component 277 */ 278 int getNameCount(); 279 280 /** 281 * Returns a name element of this path as a {@code Path} object. 282 * 283 * <p> The {@code index} parameter is the index of the name element to return. 284 * The element that is <em>closest</em> to the root in the directory hierarchy 285 * has index {@code 0}. The element that is <em>farthest</em> from the root 286 * has index {@link #getNameCount count}{@code -1}. 287 * 288 * @param index 289 * the index of the element 290 * 291 * @return the name element 292 * 293 * @throws IllegalArgumentException 294 * if {@code index} is negative, {@code index} is greater than or 295 * equal to the number of elements, or this path has zero name 296 * elements 297 */ 298 Path getName(int index); 299 300 /** 301 * Returns a relative {@code Path} that is a subsequence of the name 302 * elements of this path. 303 * 304 * <p> The {@code beginIndex} and {@code endIndex} parameters specify the 305 * subsequence of name elements. The name that is <em>closest</em> to the root 306 * in the directory hierarchy has index {@code 0}. The name that is 307 * <em>farthest</em> from the root has index {@link #getNameCount 308 * count}{@code -1}. The returned {@code Path} object has the name elements 309 * that begin at {@code beginIndex} and extend to the element at index {@code 310 * endIndex-1}. 311 * 312 * @param beginIndex 313 * the index of the first element, inclusive 314 * @param endIndex 315 * the index of the last element, exclusive 316 * 317 * @return a new {@code Path} object that is a subsequence of the name 318 * elements in this {@code Path} 319 * 320 * @throws IllegalArgumentException 321 * if {@code beginIndex} is negative, or greater than or equal to 322 * the number of elements. If {@code endIndex} is less than or 323 * equal to {@code beginIndex}, or larger than the number of elements. 324 */ 325 Path subpath(int beginIndex, int endIndex); 326 327 /** 328 * Tests if this path starts with the given path. 329 * 330 * <p> This path <em>starts</em> with the given path if this path's root 331 * component <em>starts</em> with the root component of the given path, 332 * and this path starts with the same name elements as the given path. 333 * If the given path has more name elements than this path then {@code false} 334 * is returned. 335 * 336 * <p> Whether or not the root component of this path starts with the root 337 * component of the given path is file system specific. If this path does 338 * not have a root component and the given path has a root component then 339 * this path does not start with the given path. 340 * 341 * <p> If the given path is associated with a different {@code FileSystem} 342 * to this path then {@code false} is returned. 343 * 344 * @param other 345 * the given path 346 * 347 * @return {@code true} if this path starts with the given path; otherwise 348 * {@code false} 349 */ 350 boolean startsWith(Path other); 351 352 /** 353 * Tests if this path starts with a {@code Path}, constructed by converting 354 * the given path string, in exactly the manner specified by the {@link 355 * #startsWith(Path) startsWith(Path)} method. On UNIX for example, the path 356 * "{@code foo/bar}" starts with "{@code foo}" and "{@code foo/bar}". It 357 * does not start with "{@code f}" or "{@code fo}". 358 * 359 * @implSpec 360 * The default implementation is equivalent for this path to: 361 * <pre>{@code 362 * startsWith(getFileSystem().getPath(other)); 363 * }</pre> 364 * 365 * @param other 366 * the given path string 367 * 368 * @return {@code true} if this path starts with the given path; otherwise 369 * {@code false} 370 * 371 * @throws InvalidPathException 372 * If the path string cannot be converted to a Path. 373 */ 374 default boolean startsWith(String other) { 375 return startsWith(getFileSystem().getPath(other)); 376 } 377 378 /** 379 * Tests if this path ends with the given path. 380 * 381 * <p> If the given path has <em>N</em> elements, and no root component, 382 * and this path has <em>N</em> or more elements, then this path ends with 383 * the given path if the last <em>N</em> elements of each path, starting at 384 * the element farthest from the root, are equal. 385 * 386 * <p> If the given path has a root component then this path ends with the 387 * given path if the root component of this path <em>ends with</em> the root 388 * component of the given path, and the corresponding elements of both paths 389 * are equal. Whether or not the root component of this path ends with the 390 * root component of the given path is file system specific. If this path 391 * does not have a root component and the given path has a root component 392 * then this path does not end with the given path. 393 * 394 * <p> If the given path is associated with a different {@code FileSystem} 395 * to this path then {@code false} is returned. 396 * 397 * @param other 398 * the given path 399 * 400 * @return {@code true} if this path ends with the given path; otherwise 401 * {@code false} 402 */ 403 boolean endsWith(Path other); 404 405 /** 406 * Tests if this path ends with a {@code Path}, constructed by converting 407 * the given path string, in exactly the manner specified by the {@link 408 * #endsWith(Path) endsWith(Path)} method. On UNIX for example, the path 409 * "{@code foo/bar}" ends with "{@code foo/bar}" and "{@code bar}". It does 410 * not end with "{@code r}" or "{@code /bar}". Note that trailing separators 411 * are not taken into account, and so invoking this method on the {@code 412 * Path}"{@code foo/bar}" with the {@code String} "{@code bar/}" returns 413 * {@code true}. 414 * 415 * @implSpec 416 * The default implementation is equivalent for this path to: 417 * <pre>{@code 418 * endsWith(getFileSystem().getPath(other)); 419 * }</pre> 420 * 421 * @param other 422 * the given path string 423 * 424 * @return {@code true} if this path ends with the given path; otherwise 425 * {@code false} 426 * 427 * @throws InvalidPathException 428 * If the path string cannot be converted to a Path. 429 */ 430 default boolean endsWith(String other) { 431 return endsWith(getFileSystem().getPath(other)); 432 } 433 434 /** 435 * Returns a path that is this path with redundant name elements eliminated. 436 * 437 * <p> The precise definition of this method is implementation dependent but 438 * in general it derives from this path, a path that does not contain 439 * <em>redundant</em> name elements. In many file systems, the "{@code .}" 440 * and "{@code ..}" are special names used to indicate the current directory 441 * and parent directory. In such file systems all occurrences of "{@code .}" 442 * are considered redundant. If a "{@code ..}" is preceded by a 443 * non-"{@code ..}" name then both names are considered redundant (the 444 * process to identify such names is repeated until it is no longer 445 * applicable). 446 * 447 * <p> This method does not access the file system; the path may not locate 448 * a file that exists. Eliminating "{@code ..}" and a preceding name from a 449 * path may result in the path that locates a different file than the original 450 * path. This can arise when the preceding name is a symbolic link. 451 * 452 * @return the resulting path or this path if it does not contain 453 * redundant name elements; an empty path is returned if this path 454 * does not have a root component and all name elements are redundant 455 * 456 * @see #getParent 457 * @see #toRealPath 458 */ 459 Path normalize(); 460 461 // -- resolution and relativization -- 462 463 /** 464 * Resolve the given path against this path. 465 * 466 * <p> If the {@code other} parameter is an {@link #isAbsolute() absolute} 467 * path then this method trivially returns {@code other}. If {@code other} 468 * is an <i>empty path</i> then this method trivially returns this path. 469 * Otherwise this method considers this path to be a directory and resolves 470 * the given path against this path. In the simplest case, the given path 471 * does not have a {@link #getRoot root} component, in which case this method 472 * <em>joins</em> the given path to this path and returns a resulting path 473 * that {@link #endsWith ends} with the given path. Where the given path has 474 * a root component then resolution is highly implementation dependent and 475 * therefore unspecified. 476 * 477 * @param other 478 * the path to resolve against this path 479 * 480 * @return the resulting path 481 * 482 * @see #relativize 483 */ 484 Path resolve(Path other); 485 486 /** 487 * Converts a given path string to a {@code Path} and resolves it against 488 * this {@code Path} in exactly the manner specified by the {@link 489 * #resolve(Path) resolve} method. For example, suppose that the name 490 * separator is "{@code /}" and a path represents "{@code foo/bar}", then 491 * invoking this method with the path string "{@code gus}" will result in 492 * the {@code Path} "{@code foo/bar/gus}". 493 * 494 * @implSpec 495 * The default implementation is equivalent for this path to: 496 * <pre>{@code 497 * resolve(getFileSystem().getPath(other)); 498 * }</pre> 499 * 500 * @param other 501 * the path string to resolve against this path 502 * 503 * @return the resulting path 504 * 505 * @throws InvalidPathException 506 * if the path string cannot be converted to a Path. 507 * 508 * @see FileSystem#getPath 509 */ 510 default Path resolve(String other) { 511 return resolve(getFileSystem().getPath(other)); 512 } 513 514 /** 515 * Resolves the given path against this path's {@link #getParent parent} 516 * path. This is useful where a file name needs to be <i>replaced</i> with 517 * another file name. For example, suppose that the name separator is 518 * "{@code /}" and a path represents "{@code dir1/dir2/foo}", then invoking 519 * this method with the {@code Path} "{@code bar}" will result in the {@code 520 * Path} "{@code dir1/dir2/bar}". If this path does not have a parent path, 521 * or {@code other} is {@link #isAbsolute() absolute}, then this method 522 * returns {@code other}. If {@code other} is an empty path then this method 523 * returns this path's parent, or where this path doesn't have a parent, the 524 * empty path. 525 * 526 * @implSpec 527 * The default implementation is equivalent for this path to: 528 * <pre>{@code 529 * (getParent() == null) ? other : getParent().resolve(other); 530 * }</pre> 531 * unless {@code other == null}, in which case a 532 * {@code NullPointerException} is thrown. 533 * 534 * @param other 535 * the path to resolve against this path's parent 536 * 537 * @return the resulting path 538 * 539 * @see #resolve(Path) 540 */ 541 default Path resolveSibling(Path other) { 542 if (other == null) 543 throw new NullPointerException(); 544 Path parent = getParent(); 545 return (parent == null) ? other : parent.resolve(other); 546 } 547 548 /** 549 * Converts a given path string to a {@code Path} and resolves it against 550 * this path's {@link #getParent parent} path in exactly the manner 551 * specified by the {@link #resolveSibling(Path) resolveSibling} method. 552 * 553 * @implSpec 554 * The default implementation is equivalent for this path to: 555 * <pre>{@code 556 * resolveSibling(getFileSystem().getPath(other)); 557 * }</pre> 558 * 559 * @param other 560 * the path string to resolve against this path's parent 561 * 562 * @return the resulting path 563 * 564 * @throws InvalidPathException 565 * if the path string cannot be converted to a Path. 566 * 567 * @see FileSystem#getPath 568 */ 569 default Path resolveSibling(String other) { 570 return resolveSibling(getFileSystem().getPath(other)); 571 } 572 573 /** 574 * Constructs a relative path between this path and a given path. 575 * 576 * <p> Relativization is the inverse of {@link #resolve(Path) resolution}. 577 * This method attempts to construct a {@link #isAbsolute relative} path 578 * that when {@link #resolve(Path) resolved} against this path, yields a 579 * path that locates the same file as the given path. For example, on UNIX, 580 * if this path is {@code "/a/b"} and the given path is {@code "/a/b/c/d"} 581 * then the resulting relative path would be {@code "c/d"}. Where this 582 * path and the given path do not have a {@link #getRoot root} component, 583 * then a relative path can be constructed. A relative path cannot be 584 * constructed if only one of the paths have a root component. Where both 585 * paths have a root component then it is implementation dependent if a 586 * relative path can be constructed. If this path and the given path are 587 * {@link #equals equal} then an <i>empty path</i> is returned. 588 * 589 * <p> For any two {@link #normalize normalized} paths <i>p</i> and 590 * <i>q</i>, where <i>q</i> does not have a root component, 591 * <blockquote> 592 * <i>p</i>{@code .relativize(}<i>p</i> 593 * {@code .resolve(}<i>q</i>{@code )).equals(}<i>q</i>{@code )} 594 * </blockquote> 595 * 596 * <p> When symbolic links are supported, then whether the resulting path, 597 * when resolved against this path, yields a path that can be used to locate 598 * the {@link Files#isSameFile same} file as {@code other} is implementation 599 * dependent. For example, if this path is {@code "/a/b"} and the given 600 * path is {@code "/a/x"} then the resulting relative path may be {@code 601 * "../x"}. If {@code "b"} is a symbolic link then is implementation 602 * dependent if {@code "a/b/../x"} would locate the same file as {@code "/a/x"}. 603 * 604 * @param other 605 * the path to relativize against this path 606 * 607 * @return the resulting relative path, or an empty path if both paths are 608 * equal 609 * 610 * @throws IllegalArgumentException 611 * if {@code other} is not a {@code Path} that can be relativized 612 * against this path 613 */ 614 Path relativize(Path other); 615 616 /** 617 * Returns a URI to represent this path. 618 * 619 * <p> This method constructs an absolute {@link URI} with a {@link 620 * URI#getScheme() scheme} equal to the URI scheme that identifies the 621 * provider. The exact form of the scheme specific part is highly provider 622 * dependent. 623 * 624 * <p> In the case of the default provider, the URI is hierarchical with 625 * a {@link URI#getPath() path} component that is absolute. The query and 626 * fragment components are undefined. Whether the authority component is 627 * defined or not is implementation dependent. There is no guarantee that 628 * the {@code URI} may be used to construct a {@link java.io.File java.io.File}. 629 * In particular, if this path represents a Universal Naming Convention (UNC) 630 * path, then the UNC server name may be encoded in the authority component 631 * of the resulting URI. In the case of the default provider, and the file 632 * exists, and it can be determined that the file is a directory, then the 633 * resulting {@code URI} will end with a slash. 634 * 635 * <p> The default provider provides a similar <em>round-trip</em> guarantee 636 * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it 637 * is guaranteed that 638 * <blockquote> 639 * {@link Path#get(URI) Path.get}{@code (}<i>p</i>{@code .toUri()).equals(}<i>p</i> 640 * {@code .}{@link #toAbsolutePath() toAbsolutePath}{@code ())} 641 * </blockquote> 642 * so long as the original {@code Path}, the {@code URI}, and the new {@code 643 * Path} are all created in (possibly different invocations of) the same 644 * Java virtual machine. Whether other providers make any guarantees is 645 * provider specific and therefore unspecified. 646 * 647 * <p> When a file system is constructed to access the contents of a file 648 * as a file system then it is highly implementation specific if the returned 649 * URI represents the given path in the file system or it represents a 650 * <em>compound</em> URI that encodes the URI of the enclosing file system. 651 * A format for compound URIs is not defined in this release; such a scheme 652 * may be added in a future release. 653 * 654 * @return the URI representing this path 655 * 656 * @throws java.io.IOError 657 * if an I/O error occurs obtaining the absolute path, or where a 658 * file system is constructed to access the contents of a file as 659 * a file system, and the URI of the enclosing file system cannot be 660 * obtained 661 * 662 * @throws SecurityException 663 * In the case of the default provider, and a security manager 664 * is installed, the {@link #toAbsolutePath toAbsolutePath} method 665 * throws a security exception. 666 */ 667 URI toUri(); 668 669 /** 670 * Returns a {@code Path} object representing the absolute path of this 671 * path. 672 * 673 * <p> If this path is already {@link Path#isAbsolute absolute} then this 674 * method simply returns this path. Otherwise, this method resolves the path 675 * in an implementation dependent manner, typically by resolving the path 676 * against a file system default directory. Depending on the implementation, 677 * this method may throw an I/O error if the file system is not accessible. 678 * 679 * @return a {@code Path} object representing the absolute path 680 * 681 * @throws java.io.IOError 682 * if an I/O error occurs 683 * @throws SecurityException 684 * In the case of the default provider, a security manager 685 * is installed, and this path is not absolute, then the security 686 * manager's {@link SecurityManager#checkPropertyAccess(String) 687 * checkPropertyAccess} method is invoked to check access to the 688 * system property {@code user.dir} 689 */ 690 Path toAbsolutePath(); 691 692 /** 693 * Returns the <em>real</em> path of an existing file. 694 * 695 * <p> The precise definition of this method is implementation dependent but 696 * in general it derives from this path, an {@link #isAbsolute absolute} 697 * path that locates the {@link Files#isSameFile same} file as this path, but 698 * with name elements that represent the actual name of the directories 699 * and the file. For example, where filename comparisons on a file system 700 * are case insensitive then the name elements represent the names in their 701 * actual case. Additionally, the resulting path has redundant name 702 * elements removed. 703 * 704 * <p> If this path is relative then its absolute path is first obtained, 705 * as if by invoking the {@link #toAbsolutePath toAbsolutePath} method. 706 * 707 * <p> The {@code options} array may be used to indicate how symbolic links 708 * are handled. By default, symbolic links are resolved to their final 709 * target. If the option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is 710 * present then this method does not resolve symbolic links. 711 * 712 * Some implementations allow special names such as "{@code ..}" to refer to 713 * the parent directory. When deriving the <em>real path</em>, and a 714 * "{@code ..}" (or equivalent) is preceded by a non-"{@code ..}" name then 715 * an implementation will typically cause both names to be removed. When 716 * not resolving symbolic links and the preceding name is a symbolic link 717 * then the names are only removed if it guaranteed that the resulting path 718 * will locate the same file as this path. 719 * 720 * @param options 721 * options indicating how symbolic links are handled 722 * 723 * @return an absolute path represent the <em>real</em> path of the file 724 * located by this object 725 * 726 * @throws IOException 727 * if the file does not exist or an I/O error occurs 728 * @throws SecurityException 729 * In the case of the default provider, and a security manager 730 * is installed, its {@link SecurityManager#checkRead(String) checkRead} 731 * method is invoked to check read access to the file, and where 732 * this path is not absolute, its {@link SecurityManager#checkPropertyAccess(String) 733 * checkPropertyAccess} method is invoked to check access to the 734 * system property {@code user.dir} 735 */ 736 Path toRealPath(LinkOption... options) throws IOException; 737 738 /** 739 * Returns a {@link File} object representing this path. Where this {@code 740 * Path} is associated with the default provider, then this method is 741 * equivalent to returning a {@code File} object constructed with the 742 * {@code String} representation of this path. 743 * 744 * <p> If this path was created by invoking the {@code File} {@link 745 * File#toPath toPath} method then there is no guarantee that the {@code 746 * File} object returned by this method is {@link #equals equal} to the 747 * original {@code File}. 748 * 749 * @implSpec 750 * The default implementation is equivalent for this path to: 751 * <pre>{@code 752 * new File(toString()); 753 * }</pre> 754 * if the {@code FileSystem} which created this {@code Path} is the default 755 * file system; otherwise an {@code UnsupportedOperationException} is 756 * thrown. 757 * 758 * @return a {@code File} object representing this path 759 * 760 * @throws UnsupportedOperationException 761 * if this {@code Path} is not associated with the default provider 762 */ 763 default File toFile() { 764 if (getFileSystem() == FileSystems.getDefault()) { 765 return new File(toString()); 766 } else { 767 throw new UnsupportedOperationException("Path not associated with " 768 + "default file system."); 769 } 770 } 771 772 // -- watchable -- 773 774 /** 775 * Registers the file located by this path with a watch service. 776 * 777 * <p> In this release, this path locates a directory that exists. The 778 * directory is registered with the watch service so that entries in the 779 * directory can be watched. The {@code events} parameter is the events to 780 * register and may contain the following events: 781 * <ul> 782 * <li>{@link StandardWatchEventKinds#ENTRY_CREATE ENTRY_CREATE} - 783 * entry created or moved into the directory</li> 784 * <li>{@link StandardWatchEventKinds#ENTRY_DELETE ENTRY_DELETE} - 785 * entry deleted or moved out of the directory</li> 786 * <li>{@link StandardWatchEventKinds#ENTRY_MODIFY ENTRY_MODIFY} - 787 * entry in directory was modified</li> 788 * </ul> 789 * 790 * <p> The {@link WatchEvent#context context} for these events is the 791 * relative path between the directory located by this path, and the path 792 * that locates the directory entry that is created, deleted, or modified. 793 * 794 * <p> The set of events may include additional implementation specific 795 * event that are not defined by the enum {@link StandardWatchEventKinds} 796 * 797 * <p> The {@code modifiers} parameter specifies <em>modifiers</em> that 798 * qualify how the directory is registered. This release does not define any 799 * <em>standard</em> modifiers. It may contain implementation specific 800 * modifiers. 801 * 802 * <p> Where a file is registered with a watch service by means of a symbolic 803 * link then it is implementation specific if the watch continues to depend 804 * on the existence of the symbolic link after it is registered. 805 * 806 * @param watcher 807 * the watch service to which this object is to be registered 808 * @param events 809 * the events for which this object should be registered 810 * @param modifiers 811 * the modifiers, if any, that modify how the object is registered 812 * 813 * @return a key representing the registration of this object with the 814 * given watch service 815 * 816 * @throws UnsupportedOperationException 817 * if unsupported events or modifiers are specified 818 * @throws IllegalArgumentException 819 * if an invalid combination of events or modifiers is specified 820 * @throws ClosedWatchServiceException 821 * if the watch service is closed 822 * @throws NotDirectoryException 823 * if the file is registered to watch the entries in a directory 824 * and the file is not a directory <i>(optional specific exception)</i> 825 * @throws IOException 826 * if an I/O error occurs 827 * @throws SecurityException 828 * In the case of the default provider, and a security manager is 829 * installed, the {@link SecurityManager#checkRead(String) checkRead} 830 * method is invoked to check read access to the file. 831 */ 832 @Override 833 WatchKey register(WatchService watcher, 834 WatchEvent.Kind<?>[] events, 835 WatchEvent.Modifier... modifiers) 836 throws IOException; 837 838 /** 839 * Registers the file located by this path with a watch service. 840 * 841 * <p> An invocation of this method behaves in exactly the same way as the 842 * invocation 843 * <pre> 844 * watchable.{@link #register(WatchService,WatchEvent.Kind[],WatchEvent.Modifier[]) register}(watcher, events, new WatchEvent.Modifier[0]); 845 * </pre> 846 * 847 * <p> <b>Usage Example:</b> 848 * Suppose we wish to register a directory for entry create, delete, and modify 849 * events: 850 * <pre> 851 * Path dir = ... 852 * WatchService watcher = ... 853 * 854 * WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); 855 * </pre> 856 * 857 * @implSpec 858 * The default implementation is equivalent for this path to: 859 * <pre>{@code 860 * register(watcher, events, new WatchEvent.Modifier[0]); 861 * }</pre> 862 * 863 * @param watcher 864 * The watch service to which this object is to be registered 865 * @param events 866 * The events for which this object should be registered 867 * 868 * @return A key representing the registration of this object with the 869 * given watch service 870 * 871 * @throws UnsupportedOperationException 872 * If unsupported events are specified 873 * @throws IllegalArgumentException 874 * If an invalid combination of events is specified 875 * @throws ClosedWatchServiceException 876 * If the watch service is closed 877 * @throws NotDirectoryException 878 * If the file is registered to watch the entries in a directory 879 * and the file is not a directory <i>(optional specific exception)</i> 880 * @throws IOException 881 * If an I/O error occurs 882 * @throws SecurityException 883 * In the case of the default provider, and a security manager is 884 * installed, the {@link SecurityManager#checkRead(String) checkRead} 885 * method is invoked to check read access to the file. 886 */ 887 @Override 888 default WatchKey register(WatchService watcher, 889 WatchEvent.Kind<?>... events) throws IOException { 890 return register(watcher, events, new WatchEvent.Modifier[0]); 891 } 892 893 // -- Iterable -- 894 895 /** 896 * Returns an iterator over the name elements of this path. 897 * 898 * <p> The first element returned by the iterator represents the name 899 * element that is closest to the root in the directory hierarchy, the 900 * second element is the next closest, and so on. The last element returned 901 * is the name of the file or directory denoted by this path. The {@link 902 * #getRoot root} component, if present, is not returned by the iterator. 903 * 904 * @implSpec 905 * The default implementation returns an {@code Iterator<Path>} which, for 906 * this path, traverses the {@code Path}s returned by 907 * {@code getName(index)}, where {@code index} ranges from zero to 908 * {@code getNameCount() - 1}, inclusive. 909 * 910 * @return an iterator over the name elements of this path. 911 */ 912 @Override 913 default Iterator<Path> iterator() { 914 return new Iterator<>() { 915 private int i = 0; 916 917 @Override 918 public boolean hasNext() { 919 return (i < getNameCount()); 920 } 921 922 @Override 923 public Path next() { 924 if (i < getNameCount()) { 925 Path result = getName(i); 926 i++; 927 return result; 928 } else { 929 throw new NoSuchElementException(); 930 } 931 } 932 }; 933 } 934 935 // -- compareTo/equals/hashCode -- 936 937 /** 938 * Compares two abstract paths lexicographically. The ordering defined by 939 * this method is provider specific, and in the case of the default 940 * provider, platform specific. This method does not access the file system 941 * and neither file is required to exist. 942 * 943 * <p> This method may not be used to compare paths that are associated 944 * with different file system providers. 945 * 946 * @param other the path compared to this path. 947 * 948 * @return zero if the argument is {@link #equals equal} to this path, a 949 * value less than zero if this path is lexicographically less than 950 * the argument, or a value greater than zero if this path is 951 * lexicographically greater than the argument 952 * 953 * @throws ClassCastException 954 * if the paths are associated with different providers 955 */ 956 @Override 957 int compareTo(Path other); 958 959 /** 960 * Tests this path for equality with the given object. 961 * 962 * <p> If the given object is not a Path, or is a Path associated with a 963 * different {@code FileSystem}, then this method returns {@code false}. 964 * 965 * <p> Whether or not two path are equal depends on the file system 966 * implementation. In some cases the paths are compared without regard 967 * to case, and others are case sensitive. This method does not access the 968 * file system and the file is not required to exist. Where required, the 969 * {@link Files#isSameFile isSameFile} method may be used to check if two 970 * paths locate the same file. 971 * 972 * <p> This method satisfies the general contract of the {@link 973 * java.lang.Object#equals(Object) Object.equals} method. </p> 974 * 975 * @param other 976 * the object to which this object is to be compared 977 * 978 * @return {@code true} if, and only if, the given object is a {@code Path} 979 * that is identical to this {@code Path} 980 */ 981 boolean equals(Object other); 982 983 /** 984 * Computes a hash code for this path. 985 * 986 * <p> The hash code is based upon the components of the path, and 987 * satisfies the general contract of the {@link Object#hashCode 988 * Object.hashCode} method. 989 * 990 * @return the hash-code value for this path 991 */ 992 int hashCode(); 993 994 /** 995 * Returns the string representation of this path. 996 * 997 * <p> If this path was created by converting a path string using the 998 * {@link FileSystem#getPath getPath} method then the path string returned 999 * by this method may differ from the original String used to create the path. 1000 * 1001 * <p> The returned path string uses the default name {@link 1002 * FileSystem#getSeparator separator} to separate names in the path. 1003 * 1004 * @return the string representation of this path 1005 */ 1006 String toString(); 1007 }