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