1 /* 2 * Copyright (c) 2007, 2011, 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.nio.file.attribute.*; 29 import java.nio.file.spi.FileSystemProvider; 30 import java.nio.file.spi.FileTypeDetector; 31 import java.nio.channels.Channels; 32 import java.nio.channels.FileChannel; 33 import java.nio.channels.SeekableByteChannel; 34 import java.io.InputStream; 35 import java.io.OutputStream; 36 import java.io.Reader; 37 import java.io.Writer; 38 import java.io.BufferedReader; 39 import java.io.BufferedWriter; 40 import java.io.InputStreamReader; 41 import java.io.OutputStreamWriter; 42 import java.io.IOException; 43 import java.util.*; 44 import java.security.AccessController; 45 import java.security.PrivilegedAction; 46 import java.nio.charset.Charset; 47 import java.nio.charset.CharsetDecoder; 48 import java.nio.charset.CharsetEncoder; 49 50 /** 51 * This class consists exclusively of static methods that operate on files, 52 * directories, or other types of files. 53 * 54 * <p> In most cases, the methods defined here will delegate to the associated 55 * file system provider to perform the file operations. 56 * 57 * @since 1.7 58 */ 59 60 public final class Files { 61 private Files() { } 62 63 /** 64 * Returns the {@code FileSystemProvider} to delegate to. 65 */ 66 private static FileSystemProvider provider(Path path) { 67 return path.getFileSystem().provider(); 68 } 69 70 // -- File contents -- 71 72 /** 73 * Opens a file, returning an input stream to read from the file. The stream 74 * will not be buffered, and is not required to support the {@link 75 * InputStream#mark mark} or {@link InputStream#reset reset} methods. The 76 * stream will be safe for access by multiple concurrent threads. Reading 77 * commences at the beginning of the file. Whether the returned stream is 78 * <i>asynchronously closeable</i> and/or <i>interruptible</i> is highly 79 * file system provider specific and therefore not specified. 80 * 81 * <p> The {@code options} parameter determines how the file is opened. 82 * If no options are present then it is equivalent to opening the file with 83 * the {@link StandardOpenOption#READ READ} option. In addition to the {@code 84 * READ} option, an implementation may also support additional implementation 85 * specific options. 86 * 87 * @param path 88 * the path to the file to open 89 * @param options 90 * options specifying how the file is opened 91 * 92 * @return a new input stream 93 * 94 * @throws IllegalArgumentException 95 * if an invalid combination of options is specified 96 * @throws UnsupportedOperationException 97 * if an unsupported option is specified 98 * @throws IOException 99 * if an I/O error occurs 100 * @throws SecurityException 101 * In the case of the default provider, and a security manager is 102 * installed, the {@link SecurityManager#checkRead(String) checkRead} 103 * method is invoked to check read access to the file. 104 */ 105 public static InputStream newInputStream(Path path, OpenOption... options) 106 throws IOException 107 { 108 return provider(path).newInputStream(path, options); 109 } 110 111 /** 112 * Opens or creates a file, returning an output stream that may be used to 113 * write bytes to the file. The resulting stream will not be buffered. The 114 * stream will be safe for access by multiple concurrent threads. Whether 115 * the returned stream is <i>asynchronously closeable</i> and/or 116 * <i>interruptible</i> is highly file system provider specific and 117 * therefore not specified. 118 * 119 * <p> This method opens or creates a file in exactly the manner specified 120 * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel} 121 * method with the exception that the {@link StandardOpenOption#READ READ} 122 * option may not be present in the array of options. If no options are 123 * present then this method works as if the {@link StandardOpenOption#CREATE 124 * CREATE}, {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, 125 * and {@link StandardOpenOption#WRITE WRITE} options are present. In other 126 * words, it opens the file for writing, creating the file if it doesn't 127 * exist, or initially truncating an existing {@link #isRegularFile 128 * regular-file} to a size of {@code 0} if it exists. 129 * 130 * <p> <b>Usage Examples:</b> 131 * <pre> 132 * Path path = ... 133 * 134 * // truncate and overwrite an existing file, or create the file if 135 * // it doesn't initially exist 136 * OutputStream out = Files.newOutputStream(path); 137 * 138 * // append to an existing file, fail if the file does not exist 139 * out = Files.newOutputStream(path, APPEND); 140 * 141 * // append to an existing file, create file if it doesn't initially exist 142 * out = Files.newOutputStream(path, CREATE, APPEND); 143 * 144 * // always create new file, failing if it already exists 145 * out = Files.newOutputStream(path, CREATE_NEW); 146 * </pre> 147 * 148 * @param path 149 * the path to the file to open or create 150 * @param options 151 * options specifying how the file is opened 152 * 153 * @return a new output stream 154 * 155 * @throws IllegalArgumentException 156 * if {@code options} contains an invalid combination of options 157 * @throws UnsupportedOperationException 158 * if an unsupported option is specified 159 * @throws IOException 160 * if an I/O error occurs 161 * @throws SecurityException 162 * In the case of the default provider, and a security manager is 163 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 164 * method is invoked to check write access to the file. The {@link 165 * SecurityManager#checkDelete(String) checkDelete} method is 166 * invoked to check delete access if the file is opened with the 167 * {@code DELETE_ON_CLOSE} option. 168 */ 169 public static OutputStream newOutputStream(Path path, OpenOption... options) 170 throws IOException 171 { 172 return provider(path).newOutputStream(path, options); 173 } 174 175 /** 176 * Opens or creates a file, returning a seekable byte channel to access the 177 * file. 178 * 179 * <p> The {@code options} parameter determines how the file is opened. 180 * The {@link StandardOpenOption#READ READ} and {@link 181 * StandardOpenOption#WRITE WRITE} options determine if the file should be 182 * opened for reading and/or writing. If neither option (or the {@link 183 * StandardOpenOption#APPEND APPEND} option) is present then the file is 184 * opened for reading. By default reading or writing commence at the 185 * beginning of the file. 186 * 187 * <p> In the addition to {@code READ} and {@code WRITE}, the following 188 * options may be present: 189 * 190 * <table border=1 cellpadding=5 summary=""> 191 * <tr> <th>Option</th> <th>Description</th> </tr> 192 * <tr> 193 * <td> {@link StandardOpenOption#APPEND APPEND} </td> 194 * <td> If this option is present then the file is opened for writing and 195 * each invocation of the channel's {@code write} method first advances 196 * the position to the end of the file and then writes the requested 197 * data. Whether the advancement of the position and the writing of the 198 * data are done in a single atomic operation is system-dependent and 199 * therefore unspecified. This option may not be used in conjunction 200 * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> 201 * </tr> 202 * <tr> 203 * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> 204 * <td> If this option is present then the existing file is truncated to 205 * a size of 0 bytes. This option is ignored when the file is opened only 206 * for reading. </td> 207 * </tr> 208 * <tr> 209 * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> 210 * <td> If this option is present then a new file is created, failing if 211 * the file already exists or is a symbolic link. When creating a file the 212 * check for the existence of the file and the creation of the file if it 213 * does not exist is atomic with respect to other file system operations. 214 * This option is ignored when the file is opened only for reading. </td> 215 * </tr> 216 * <tr> 217 * <td > {@link StandardOpenOption#CREATE CREATE} </td> 218 * <td> If this option is present then an existing file is opened if it 219 * exists, otherwise a new file is created. This option is ignored if the 220 * {@code CREATE_NEW} option is also present or the file is opened only 221 * for reading. </td> 222 * </tr> 223 * <tr> 224 * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> 225 * <td> When this option is present then the implementation makes a 226 * <em>best effort</em> attempt to delete the file when closed by the 227 * {@link SeekableByteChannel#close close} method. If the {@code close} 228 * method is not invoked then a <em>best effort</em> attempt is made to 229 * delete the file when the Java virtual machine terminates. </td> 230 * </tr> 231 * <tr> 232 * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> 233 * <td> When creating a new file this option is a <em>hint</em> that the 234 * new file will be sparse. This option is ignored when not creating 235 * a new file. </td> 236 * </tr> 237 * <tr> 238 * <td> {@link StandardOpenOption#SYNC SYNC} </td> 239 * <td> Requires that every update to the file's content or metadata be 240 * written synchronously to the underlying storage device. (see <a 241 * href="package-summary.html#integrity"> Synchronized I/O file 242 * integrity</a>). </td> 243 * <tr> 244 * <tr> 245 * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> 246 * <td> Requires that every update to the file's content be written 247 * synchronously to the underlying storage device. (see <a 248 * href="package-summary.html#integrity"> Synchronized I/O file 249 * integrity</a>). </td> 250 * </tr> 251 * </table> 252 * 253 * <p> An implementation may also support additional implementation specific 254 * options. 255 * 256 * <p> The {@code attrs} parameter is optional {@link FileAttribute 257 * file-attributes} to set atomically when a new file is created. 258 * 259 * <p> In the case of the default provider, the returned seekable byte channel 260 * is a {@link java.nio.channels.FileChannel}. 261 * 262 * <p> <b>Usage Examples:</b> 263 * <pre> 264 * Path path = ... 265 * 266 * // open file for reading 267 * ReadableByteChannel rbc = Files.newByteChannel(path, EnumSet.of(READ))); 268 * 269 * // open file for writing to the end of an existing file, creating 270 * // the file if it doesn't already exist 271 * WritableByteChannel wbc = Files.newByteChannel(path, EnumSet.of(CREATE,APPEND)); 272 * 273 * // create file with initial permissions, opening it for both reading and writing 274 * {@code FileAttribute<<SetPosixFilePermission>> perms = ...} 275 * SeekableByteChannel sbc = Files.newByteChannel(path, EnumSet.of(CREATE_NEW,READ,WRITE), perms); 276 * </pre> 277 * 278 * @param path 279 * the path to the file to open or create 280 * @param options 281 * options specifying how the file is opened 282 * @param attrs 283 * an optional list of file attributes to set atomically when 284 * creating the file 285 * 286 * @return a new seekable byte channel 287 * 288 * @throws IllegalArgumentException 289 * if the set contains an invalid combination of options 290 * @throws UnsupportedOperationException 291 * if an unsupported open option is specified or the array contains 292 * attributes that cannot be set atomically when creating the file 293 * @throws FileAlreadyExistsException 294 * if a file of that name already exists and the {@link 295 * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified 296 * <i>(optional specific exception)</i> 297 * @throws IOException 298 * if an I/O error occurs 299 * @throws SecurityException 300 * In the case of the default provider, and a security manager is 301 * installed, the {@link SecurityManager#checkRead(String) checkRead} 302 * method is invoked to check read access to the path if the file is 303 * opened for reading. The {@link SecurityManager#checkWrite(String) 304 * checkWrite} method is invoked to check write access to the path 305 * if the file is opened for writing. The {@link 306 * SecurityManager#checkDelete(String) checkDelete} method is 307 * invoked to check delete access if the file is opened with the 308 * {@code DELETE_ON_CLOSE} option. 309 * 310 * @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[]) 311 */ 312 public static SeekableByteChannel newByteChannel(Path path, 313 Set<? extends OpenOption> options, 314 FileAttribute<?>... attrs) 315 throws IOException 316 { 317 return provider(path).newByteChannel(path, options, attrs); 318 } 319 320 /** 321 * Opens or creates a file, returning a seekable byte channel to access the 322 * file. 323 * 324 * <p> This method opens or creates a file in exactly the manner specified 325 * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel} 326 * method. 327 * 328 * @param path 329 * the path to the file to open or create 330 * @param options 331 * options specifying how the file is opened 332 * 333 * @return a new seekable byte channel 334 * 335 * @throws IllegalArgumentException 336 * if the set contains an invalid combination of options 337 * @throws UnsupportedOperationException 338 * if an unsupported open option is specified 339 * @throws FileAlreadyExistsException 340 * if a file of that name already exists and the {@link 341 * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified 342 * <i>(optional specific exception)</i> 343 * @throws IOException 344 * if an I/O error occurs 345 * @throws SecurityException 346 * In the case of the default provider, and a security manager is 347 * installed, the {@link SecurityManager#checkRead(String) checkRead} 348 * method is invoked to check read access to the path if the file is 349 * opened for reading. The {@link SecurityManager#checkWrite(String) 350 * checkWrite} method is invoked to check write access to the path 351 * if the file is opened for writing. The {@link 352 * SecurityManager#checkDelete(String) checkDelete} method is 353 * invoked to check delete access if the file is opened with the 354 * {@code DELETE_ON_CLOSE} option. 355 * 356 * @see java.nio.channels.FileChannel#open(Path,OpenOption[]) 357 */ 358 public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) 359 throws IOException 360 { 361 Set<OpenOption> set = new HashSet<OpenOption>(options.length); 362 Collections.addAll(set, options); 363 return newByteChannel(path, set); 364 } 365 366 // -- Directories -- 367 368 private static class AcceptAllFilter 369 implements DirectoryStream.Filter<Path> 370 { 371 private AcceptAllFilter() { } 372 373 @Override 374 public boolean accept(Path entry) { return true; } 375 376 static final AcceptAllFilter FILTER = new AcceptAllFilter(); 377 } 378 379 /** 380 * Opens a directory, returning a {@link DirectoryStream} to iterate over 381 * all entries in the directory. The elements returned by the directory 382 * stream's {@link DirectoryStream#iterator iterator} are of type {@code 383 * Path}, each one representing an entry in the directory. The {@code Path} 384 * objects are obtained as if by {@link Path#resolve(Path) resolving} the 385 * name of the directory entry against {@code dir}. 386 * 387 * <p> When not using the try-with-resources construct, then directory 388 * stream's {@code close} method should be invoked after iteration is 389 * completed so as to free any resources held for the open directory. 390 * 391 * <p> When an implementation supports operations on entries in the 392 * directory that execute in a race-free manner then the returned directory 393 * stream is a {@link SecureDirectoryStream}. 394 * 395 * @param dir 396 * the path to the directory 397 * 398 * @return a new and open {@code DirectoryStream} object 399 * 400 * @throws NotDirectoryException 401 * if the file could not otherwise be opened because it is not 402 * a directory <i>(optional specific exception)</i> 403 * @throws IOException 404 * if an I/O error occurs 405 * @throws SecurityException 406 * In the case of the default provider, and a security manager is 407 * installed, the {@link SecurityManager#checkRead(String) checkRead} 408 * method is invoked to check read access to the directory. 409 */ 410 public static DirectoryStream<Path> newDirectoryStream(Path dir) 411 throws IOException 412 { 413 return provider(dir).newDirectoryStream(dir, AcceptAllFilter.FILTER); 414 } 415 416 /** 417 * Opens a directory, returning a {@link DirectoryStream} to iterate over 418 * the entries in the directory. The elements returned by the directory 419 * stream's {@link DirectoryStream#iterator iterator} are of type {@code 420 * Path}, each one representing an entry in the directory. The {@code Path} 421 * objects are obtained as if by {@link Path#resolve(Path) resolving} the 422 * name of the directory entry against {@code dir}. The entries returned by 423 * the iterator are filtered by matching the {@code String} representation 424 * of their file names against the given <em>globbing</em> pattern. 425 * 426 * <p> For example, suppose we want to iterate over the files ending with 427 * ".java" in a directory: 428 * <pre> 429 * Path dir = ... 430 * try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")) { 431 * : 432 * } 433 * </pre> 434 * 435 * <p> The globbing pattern is specified by the {@link 436 * FileSystem#getPathMatcher getPathMatcher} method. 437 * 438 * <p> When not using the try-with-resources construct, then directory 439 * stream's {@code close} method should be invoked after iteration is 440 * completed so as to free any resources held for the open directory. 441 * 442 * <p> When an implementation supports operations on entries in the 443 * directory that execute in a race-free manner then the returned directory 444 * stream is a {@link SecureDirectoryStream}. 445 * 446 * @param dir 447 * the path to the directory 448 * @param glob 449 * the glob pattern 450 * 451 * @return a new and open {@code DirectoryStream} object 452 * 453 * @throws java.util.regex.PatternSyntaxException 454 * if the pattern is invalid 455 * @throws NotDirectoryException 456 * if the file could not otherwise be opened because it is not 457 * a directory <i>(optional specific exception)</i> 458 * @throws IOException 459 * if an I/O error occurs 460 * @throws SecurityException 461 * In the case of the default provider, and a security manager is 462 * installed, the {@link SecurityManager#checkRead(String) checkRead} 463 * method is invoked to check read access to the directory. 464 */ 465 public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) 466 throws IOException 467 { 468 // avoid creating a matcher if all entries are required. 469 if (glob.equals("*")) 470 return newDirectoryStream(dir); 471 472 // create a matcher and return a filter that uses it. 473 FileSystem fs = dir.getFileSystem(); 474 final PathMatcher matcher = fs.getPathMatcher("glob:" + glob); 475 DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { 476 @Override 477 public boolean accept(Path entry) { 478 return matcher.matches(entry.getFileName()); 479 } 480 }; 481 return fs.provider().newDirectoryStream(dir, filter); 482 } 483 484 /** 485 * Opens a directory, returning a {@link DirectoryStream} to iterate over 486 * the entries in the directory. The elements returned by the directory 487 * stream's {@link DirectoryStream#iterator iterator} are of type {@code 488 * Path}, each one representing an entry in the directory. The {@code Path} 489 * objects are obtained as if by {@link Path#resolve(Path) resolving} the 490 * name of the directory entry against {@code dir}. The entries returned by 491 * the iterator are filtered by the given {@link DirectoryStream.Filter 492 * filter}. 493 * 494 * <p> When not using the try-with-resources construct, then directory 495 * stream's {@code close} method should be invoked after iteration is 496 * completed so as to free any resources held for the open directory. 497 * 498 * <p> Where the filter terminates due to an uncaught error or runtime 499 * exception then it is propagated to the {@link Iterator#hasNext() 500 * hasNext} or {@link Iterator#next() next} method. Where an {@code 501 * IOException} is thrown, it results in the {@code hasNext} or {@code 502 * next} method throwing a {@link DirectoryIteratorException} with the 503 * {@code IOException} as the cause. 504 * 505 * <p> When an implementation supports operations on entries in the 506 * directory that execute in a race-free manner then the returned directory 507 * stream is a {@link SecureDirectoryStream}. 508 * 509 * <p> <b>Usage Example:</b> 510 * Suppose we want to iterate over the files in a directory that are 511 * larger than 8K. 512 * <pre> 513 * DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { 514 * public boolean accept(Path file) throws IOException { 515 * return (Files.size(file) > 8192L); 516 * } 517 * }; 518 * Path dir = ... 519 * try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) { 520 * : 521 * } 522 * </pre> 523 * 524 * @param dir 525 * the path to the directory 526 * @param filter 527 * the directory stream filter 528 * 529 * @return a new and open {@code DirectoryStream} object 530 * 531 * @throws NotDirectoryException 532 * if the file could not otherwise be opened because it is not 533 * a directory <i>(optional specific exception)</i> 534 * @throws IOException 535 * if an I/O error occurs 536 * @throws SecurityException 537 * In the case of the default provider, and a security manager is 538 * installed, the {@link SecurityManager#checkRead(String) checkRead} 539 * method is invoked to check read access to the directory. 540 */ 541 public static DirectoryStream<Path> newDirectoryStream(Path dir, 542 DirectoryStream.Filter<? super Path> filter) 543 throws IOException 544 { 545 return provider(dir).newDirectoryStream(dir, filter); 546 } 547 548 // -- Creation and deletion -- 549 550 /** 551 * Creates a new and empty file, failing if the file already exists. The 552 * check for the existence of the file and the creation of the new file if 553 * it does not exist are a single operation that is atomic with respect to 554 * all other filesystem activities that might affect the directory. 555 * 556 * <p> The {@code attrs} parameter is optional {@link FileAttribute 557 * file-attributes} to set atomically when creating the file. Each attribute 558 * is identified by its {@link FileAttribute#name name}. If more than one 559 * attribute of the same name is included in the array then all but the last 560 * occurrence is ignored. 561 * 562 * @param path 563 * the path to the file to create 564 * @param attrs 565 * an optional list of file attributes to set atomically when 566 * creating the file 567 * 568 * @return the file 569 * 570 * @throws UnsupportedOperationException 571 * if the array contains an attribute that cannot be set atomically 572 * when creating the file 573 * @throws FileAlreadyExistsException 574 * if a file of that name already exists 575 * <i>(optional specific exception)</i> 576 * @throws IOException 577 * if an I/O error occurs or the parent directory does not exist 578 * @throws SecurityException 579 * In the case of the default provider, and a security manager is 580 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 581 * method is invoked to check write access to the new file. 582 */ 583 public static Path createFile(Path path, FileAttribute<?>... attrs) 584 throws IOException 585 { 586 EnumSet<StandardOpenOption> options = 587 EnumSet.<StandardOpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); 588 newByteChannel(path, options, attrs).close(); 589 return path; 590 } 591 592 /** 593 * Creates a new directory. The check for the existence of the file and the 594 * creation of the directory if it does not exist are a single operation 595 * that is atomic with respect to all other filesystem activities that might 596 * affect the directory. The {@link #createDirectories createDirectories} 597 * method should be used where it is required to create all nonexistent 598 * parent directories first. 599 * 600 * <p> The {@code attrs} parameter is optional {@link FileAttribute 601 * file-attributes} to set atomically when creating the directory. Each 602 * attribute is identified by its {@link FileAttribute#name name}. If more 603 * than one attribute of the same name is included in the array then all but 604 * the last occurrence is ignored. 605 * 606 * @param dir 607 * the directory to create 608 * @param attrs 609 * an optional list of file attributes to set atomically when 610 * creating the directory 611 * 612 * @return the directory 613 * 614 * @throws UnsupportedOperationException 615 * if the array contains an attribute that cannot be set atomically 616 * when creating the directory 617 * @throws FileAlreadyExistsException 618 * if a directory could not otherwise be created because a file of 619 * that name already exists <i>(optional specific exception)</i> 620 * @throws IOException 621 * if an I/O error occurs or the parent directory does not exist 622 * @throws SecurityException 623 * In the case of the default provider, and a security manager is 624 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 625 * method is invoked to check write access to the new directory. 626 */ 627 public static Path createDirectory(Path dir, FileAttribute<?>... attrs) 628 throws IOException 629 { 630 provider(dir).createDirectory(dir, attrs); 631 return dir; 632 } 633 634 /** 635 * Creates a directory by creating all nonexistent parent directories first. 636 * Unlike the {@link #createDirectory createDirectory} method, an exception 637 * is not thrown if the directory could not be created because it already 638 * exists. 639 * 640 * <p> The {@code attrs} parameter is optional {@link FileAttribute 641 * file-attributes} to set atomically when creating the nonexistent 642 * directories. Each file attribute is identified by its {@link 643 * FileAttribute#name name}. If more than one attribute of the same name is 644 * included in the array then all but the last occurrence is ignored. 645 * 646 * <p> If this method fails, then it may do so after creating some, but not 647 * all, of the parent directories. 648 * 649 * @param dir 650 * the directory to create 651 * 652 * @param attrs 653 * an optional list of file attributes to set atomically when 654 * creating the directory 655 * 656 * @return the directory 657 * 658 * @throws UnsupportedOperationException 659 * if the array contains an attribute that cannot be set atomically 660 * when creating the directory 661 * @throws FileAlreadyExistsException 662 * if {@code dir} exists but is not a directory <i>(optional specific 663 * exception)</i> 664 * @throws IOException 665 * if an I/O error occurs 666 * @throws SecurityException 667 * in the case of the default provider, and a security manager is 668 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 669 * method is invoked prior to attempting to create a directory and 670 * its {@link SecurityManager#checkRead(String) checkRead} is 671 * invoked for each parent directory that is checked. If {@code 672 * dir} is not an absolute path then its {@link Path#toAbsolutePath 673 * toAbsolutePath} may need to be invoked to get its absolute path. 674 * This may invoke the security manager's {@link 675 * SecurityManager#checkPropertyAccess(String) checkPropertyAccess} 676 * method to check access to the system property {@code user.dir} 677 */ 678 public static Path createDirectories(Path dir, FileAttribute<?>... attrs) 679 throws IOException 680 { 681 // attempt to create the directory 682 try { 683 createAndCheckIsDirectory(dir, attrs); 684 return dir; 685 } catch (FileAlreadyExistsException x) { 686 // file exists and is not a directory 687 throw x; 688 } catch (IOException x) { 689 // parent may not exist or other reason 690 } 691 SecurityException se = null; 692 try { 693 dir = dir.toAbsolutePath(); 694 } catch (SecurityException x) { 695 // don't have permission to get absolute path 696 se = x; 697 } 698 // find a decendent that exists 699 Path parent = dir.getParent(); 700 while (parent != null) { 701 try { 702 provider(parent).checkAccess(parent); 703 break; 704 } catch (NoSuchFileException x) { 705 // does not exist 706 } 707 parent = parent.getParent(); 708 } 709 if (parent == null) { 710 // unable to find existing parent 711 if (se != null) 712 throw se; 713 throw new IOException("Root directory does not exist"); 714 } 715 716 // create directories 717 Path child = parent; 718 for (Path name: parent.relativize(dir)) { 719 child = child.resolve(name); 720 createAndCheckIsDirectory(child, attrs); 721 } 722 return dir; 723 } 724 725 /** 726 * Used by createDirectories to attempt to create a directory. A no-op 727 * if the directory already exists. 728 */ 729 private static void createAndCheckIsDirectory(Path dir, 730 FileAttribute<?>... attrs) 731 throws IOException 732 { 733 try { 734 createDirectory(dir, attrs); 735 } catch (FileAlreadyExistsException x) { 736 if (!isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) 737 throw x; 738 } 739 } 740 741 /** 742 * Creates a new empty file in the specified directory, using the given 743 * prefix and suffix strings to generate its name. The resulting 744 * {@code Path} is associated with the same {@code FileSystem} as the given 745 * directory. 746 * 747 * <p> The details as to how the name of the file is constructed is 748 * implementation dependent and therefore not specified. Where possible 749 * the {@code prefix} and {@code suffix} are used to construct candidate 750 * names in the same manner as the {@link 751 * java.io.File#createTempFile(String,String,File)} method. 752 * 753 * <p> As with the {@code File.createTempFile} methods, this method is only 754 * part of a temporary-file facility. Where used as a <em>work files</em>, 755 * the resulting file may be opened using the {@link 756 * StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} option so that the 757 * file is deleted when the appropriate {@code close} method is invoked. 758 * Alternatively, a {@link Runtime#addShutdownHook shutdown-hook}, or the 759 * {@link java.io.File#deleteOnExit} mechanism may be used to delete the 760 * file automatically. 761 * 762 * <p> The {@code attrs} parameter is optional {@link FileAttribute 763 * file-attributes} to set atomically when creating the file. Each attribute 764 * is identified by its {@link FileAttribute#name name}. If more than one 765 * attribute of the same name is included in the array then all but the last 766 * occurrence is ignored. When no file attributes are specified, then the 767 * resulting file may have more restrictive access permissions to files 768 * created by the {@link java.io.File#createTempFile(String,String,File)} 769 * method. 770 * 771 * @param dir 772 * the path to directory in which to create the file 773 * @param prefix 774 * the prefix string to be used in generating the file's name; 775 * may be {@code null} 776 * @param suffix 777 * the suffix string to be used in generating the file's name; 778 * may be {@code null}, in which case "{@code .tmp}" is used 779 * @param attrs 780 * an optional list of file attributes to set atomically when 781 * creating the file 782 * 783 * @return the path to the newly created file that did not exist before 784 * this method was invoked 785 * 786 * @throws IllegalArgumentException 787 * if the prefix or suffix parameters cannot be used to generate 788 * a candidate file name 789 * @throws UnsupportedOperationException 790 * if the array contains an attribute that cannot be set atomically 791 * when creating the directory 792 * @throws IOException 793 * if an I/O error occurs or {@code dir} does not exist 794 * @throws SecurityException 795 * In the case of the default provider, and a security manager is 796 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 797 * method is invoked to check write access to the file. 798 */ 799 public static Path createTempFile(Path dir, 800 String prefix, 801 String suffix, 802 FileAttribute<?>... attrs) 803 throws IOException 804 { 805 return TempFileHelper.createTempFile(Objects.requireNonNull(dir), 806 prefix, suffix, attrs); 807 } 808 809 /** 810 * Creates an empty file in the default temporary-file directory, using 811 * the given prefix and suffix to generate its name. The resulting {@code 812 * Path} is associated with the default {@code FileSystem}. 813 * 814 * <p> This method works in exactly the manner specified by the 815 * {@link #createTempFile(Path,String,String,FileAttribute[])} method for 816 * the case that the {@code dir} parameter is the temporary-file directory. 817 * 818 * @param prefix 819 * the prefix string to be used in generating the file's name; 820 * may be {@code null} 821 * @param suffix 822 * the suffix string to be used in generating the file's name; 823 * may be {@code null}, in which case "{@code .tmp}" is used 824 * @param attrs 825 * an optional list of file attributes to set atomically when 826 * creating the file 827 * 828 * @return the path to the newly created file that did not exist before 829 * this method was invoked 830 * 831 * @throws IllegalArgumentException 832 * if the prefix or suffix parameters cannot be used to generate 833 * a candidate file name 834 * @throws UnsupportedOperationException 835 * if the array contains an attribute that cannot be set atomically 836 * when creating the directory 837 * @throws IOException 838 * if an I/O error occurs or the temporary-file directory does not 839 * exist 840 * @throws SecurityException 841 * In the case of the default provider, and a security manager is 842 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 843 * method is invoked to check write access to the file. 844 */ 845 public static Path createTempFile(String prefix, 846 String suffix, 847 FileAttribute<?>... attrs) 848 throws IOException 849 { 850 return TempFileHelper.createTempFile(null, prefix, suffix, attrs); 851 } 852 853 /** 854 * Creates a new directory in the specified directory, using the given 855 * prefix to generate its name. The resulting {@code Path} is associated 856 * with the same {@code FileSystem} as the given directory. 857 * 858 * <p> The details as to how the name of the directory is constructed is 859 * implementation dependent and therefore not specified. Where possible 860 * the {@code prefix} is used to construct candidate names. 861 * 862 * <p> As with the {@code createTempFile} methods, this method is only 863 * part of a temporary-file facility. A {@link Runtime#addShutdownHook 864 * shutdown-hook}, or the {@link java.io.File#deleteOnExit} mechanism may be 865 * used to delete the directory automatically. 866 * 867 * <p> The {@code attrs} parameter is optional {@link FileAttribute 868 * file-attributes} to set atomically when creating the directory. Each 869 * attribute is identified by its {@link FileAttribute#name name}. If more 870 * than one attribute of the same name is included in the array then all but 871 * the last occurrence is ignored. 872 * 873 * @param dir 874 * the path to directory in which to create the directory 875 * @param prefix 876 * the prefix string to be used in generating the directory's name; 877 * may be {@code null} 878 * @param attrs 879 * an optional list of file attributes to set atomically when 880 * creating the directory 881 * 882 * @return the path to the newly created directory that did not exist before 883 * this method was invoked 884 * 885 * @throws IllegalArgumentException 886 * if the prefix cannot be used to generate a candidate directory name 887 * @throws UnsupportedOperationException 888 * if the array contains an attribute that cannot be set atomically 889 * when creating the directory 890 * @throws IOException 891 * if an I/O error occurs or {@code dir} does not exist 892 * @throws SecurityException 893 * In the case of the default provider, and a security manager is 894 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 895 * method is invoked to check write access when creating the 896 * directory. 897 */ 898 public static Path createTempDirectory(Path dir, 899 String prefix, 900 FileAttribute<?>... attrs) 901 throws IOException 902 { 903 return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir), 904 prefix, attrs); 905 } 906 907 /** 908 * Creates a new directory in the default temporary-file directory, using 909 * the given prefix to generate its name. The resulting {@code Path} is 910 * associated with the default {@code FileSystem}. 911 * 912 * <p> This method works in exactly the manner specified by {@link 913 * #createTempDirectory(Path,String,FileAttribute[])} method for the case 914 * that the {@code dir} parameter is the temporary-file directory. 915 * 916 * @param prefix 917 * the prefix string to be used in generating the directory's name; 918 * may be {@code null} 919 * @param attrs 920 * an optional list of file attributes to set atomically when 921 * creating the directory 922 * 923 * @return the path to the newly created directory that did not exist before 924 * this method was invoked 925 * 926 * @throws IllegalArgumentException 927 * if the prefix cannot be used to generate a candidate directory name 928 * @throws UnsupportedOperationException 929 * if the array contains an attribute that cannot be set atomically 930 * when creating the directory 931 * @throws IOException 932 * if an I/O error occurs or the temporary-file directory does not 933 * exist 934 * @throws SecurityException 935 * In the case of the default provider, and a security manager is 936 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 937 * method is invoked to check write access when creating the 938 * directory. 939 */ 940 public static Path createTempDirectory(String prefix, 941 FileAttribute<?>... attrs) 942 throws IOException 943 { 944 return TempFileHelper.createTempDirectory(null, prefix, attrs); 945 } 946 947 /** 948 * Creates a symbolic link to a target <i>(optional operation)</i>. 949 * 950 * <p> The {@code target} parameter is the target of the link. It may be an 951 * {@link Path#isAbsolute absolute} or relative path and may not exist. When 952 * the target is a relative path then file system operations on the resulting 953 * link are relative to the path of the link. 954 * 955 * <p> The {@code attrs} parameter is optional {@link FileAttribute 956 * attributes} to set atomically when creating the link. Each attribute is 957 * identified by its {@link FileAttribute#name name}. If more than one attribute 958 * of the same name is included in the array then all but the last occurrence 959 * is ignored. 960 * 961 * <p> Where symbolic links are supported, but the underlying {@link FileStore} 962 * does not support symbolic links, then this may fail with an {@link 963 * IOException}. Additionally, some operating systems may require that the 964 * Java virtual machine be started with implementation specific privileges to 965 * create symbolic links, in which case this method may throw {@code IOException}. 966 * 967 * @param link 968 * the path of the symbolic link to create 969 * @param target 970 * the target of the symbolic link 971 * @param attrs 972 * the array of attributes to set atomically when creating the 973 * symbolic link 974 * 975 * @return the path to the symbolic link 976 * 977 * @throws UnsupportedOperationException 978 * if the implementation does not support symbolic links or the 979 * array contains an attribute that cannot be set atomically when 980 * creating the symbolic link 981 * @throws FileAlreadyExistsException 982 * if a file with the name already exists <i>(optional specific 983 * exception)</i> 984 * @throws IOException 985 * if an I/O error occurs 986 * @throws SecurityException 987 * In the case of the default provider, and a security manager 988 * is installed, it denies {@link LinkPermission}<tt>("symbolic")</tt> 989 * or its {@link SecurityManager#checkWrite(String) checkWrite} 990 * method denies write access to the path of the symbolic link. 991 */ 992 public static Path createSymbolicLink(Path link, Path target, 993 FileAttribute<?>... attrs) 994 throws IOException 995 { 996 provider(link).createSymbolicLink(link, target, attrs); 997 return link; 998 } 999 1000 /** 1001 * Creates a new link (directory entry) for an existing file <i>(optional 1002 * operation)</i>. 1003 * 1004 * <p> The {@code link} parameter locates the directory entry to create. 1005 * The {@code existing} parameter is the path to an existing file. This 1006 * method creates a new directory entry for the file so that it can be 1007 * accessed using {@code link} as the path. On some file systems this is 1008 * known as creating a "hard link". Whether the file attributes are 1009 * maintained for the file or for each directory entry is file system 1010 * specific and therefore not specified. Typically, a file system requires 1011 * that all links (directory entries) for a file be on the same file system. 1012 * Furthermore, on some platforms, the Java virtual machine may require to 1013 * be started with implementation specific privileges to create hard links 1014 * or to create links to directories. 1015 * 1016 * @param link 1017 * the link (directory entry) to create 1018 * @param existing 1019 * a path to an existing file 1020 * 1021 * @return the path to the link (directory entry) 1022 * 1023 * @throws UnsupportedOperationException 1024 * if the implementation does not support adding an existing file 1025 * to a directory 1026 * @throws FileAlreadyExistsException 1027 * if the entry could not otherwise be created because a file of 1028 * that name already exists <i>(optional specific exception)</i> 1029 * @throws IOException 1030 * if an I/O error occurs 1031 * @throws SecurityException 1032 * In the case of the default provider, and a security manager 1033 * is installed, it denies {@link LinkPermission}<tt>("hard")</tt> 1034 * or its {@link SecurityManager#checkWrite(String) checkWrite} 1035 * method denies write access to either the link or the 1036 * existing file. 1037 */ 1038 public static Path createLink(Path link, Path existing) throws IOException { 1039 provider(link).createLink(link, existing); 1040 return link; 1041 } 1042 1043 /** 1044 * Deletes a file. 1045 * 1046 * <p> An implementation may require to examine the file to determine if the 1047 * file is a directory. Consequently this method may not be atomic with respect 1048 * to other file system operations. If the file is a symbolic link then the 1049 * symbolic link itself, not the final target of the link, is deleted. 1050 * 1051 * <p> If the file is a directory then the directory must be empty. In some 1052 * implementations a directory has entries for special files or links that 1053 * are created when the directory is created. In such implementations a 1054 * directory is considered empty when only the special entries exist. 1055 * This method can be used with the {@link #walkFileTree walkFileTree} 1056 * method to delete a directory and all entries in the directory, or an 1057 * entire <i>file-tree</i> where required. 1058 * 1059 * <p> On some operating systems it may not be possible to remove a file when 1060 * it is open and in use by this Java virtual machine or other programs. 1061 * 1062 * @param path 1063 * the path to the file to delete 1064 * 1065 * @throws NoSuchFileException 1066 * if the file does not exist <i>(optional specific exception)</i> 1067 * @throws DirectoryNotEmptyException 1068 * if the file is a directory and could not otherwise be deleted 1069 * because the directory is not empty <i>(optional specific 1070 * exception)</i> 1071 * @throws IOException 1072 * if an I/O error occurs 1073 * @throws SecurityException 1074 * In the case of the default provider, and a security manager is 1075 * installed, the {@link SecurityManager#checkDelete(String)} method 1076 * is invoked to check delete access to the file 1077 */ 1078 public static void delete(Path path) throws IOException { 1079 provider(path).delete(path); 1080 } 1081 1082 /** 1083 * Deletes a file if it exists. 1084 * 1085 * <p> As with the {@link #delete(Path) delete(Path)} method, an 1086 * implementation may need to examine the file to determine if the file is a 1087 * directory. Consequently this method may not be atomic with respect to 1088 * other file system operations. If the file is a symbolic link, then the 1089 * symbolic link itself, not the final target of the link, is deleted. 1090 * 1091 * <p> If the file is a directory then the directory must be empty. In some 1092 * implementations a directory has entries for special files or links that 1093 * are created when the directory is created. In such implementations a 1094 * directory is considered empty when only the special entries exist. 1095 * 1096 * <p> On some operating systems it may not be possible to remove a file when 1097 * it is open and in use by this Java virtual machine or other programs. 1098 * 1099 * @param path 1100 * the path to the file to delete 1101 * 1102 * @return {@code true} if the file was deleted by this method; {@code 1103 * false} if the file could not be deleted because it did not 1104 * exist 1105 * 1106 * @throws DirectoryNotEmptyException 1107 * if the file is a directory and could not otherwise be deleted 1108 * because the directory is not empty <i>(optional specific 1109 * exception)</i> 1110 * @throws IOException 1111 * if an I/O error occurs 1112 * @throws SecurityException 1113 * In the case of the default provider, and a security manager is 1114 * installed, the {@link SecurityManager#checkDelete(String)} method 1115 * is invoked to check delete access to the file. 1116 */ 1117 public static boolean deleteIfExists(Path path) throws IOException { 1118 return provider(path).deleteIfExists(path); 1119 } 1120 1121 // -- Copying and moving files -- 1122 1123 /** 1124 * Copy a file to a target file. 1125 * 1126 * <p> This method copies a file to the target file with the {@code 1127 * options} parameter specifying how the copy is performed. By default, the 1128 * copy fails if the target file already exists or is a symbolic link, 1129 * except if the source and target are the {@link #isSameFile same} file, in 1130 * which case the method completes without copying the file. File attributes 1131 * are not required to be copied to the target file. If symbolic links are 1132 * supported, and the file is a symbolic link, then the final target of the 1133 * link is copied. If the file is a directory then it creates an empty 1134 * directory in the target location (entries in the directory are not 1135 * copied). This method can be used with the {@link #walkFileTree 1136 * walkFileTree} method to copy a directory and all entries in the directory, 1137 * or an entire <i>file-tree</i> where required. 1138 * 1139 * <p> The {@code options} parameter may include any of the following: 1140 * 1141 * <table border=1 cellpadding=5 summary=""> 1142 * <tr> <th>Option</th> <th>Description</th> </tr> 1143 * <tr> 1144 * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td> 1145 * <td> If the target file exists, then the target file is replaced if it 1146 * is not a non-empty directory. If the target file exists and is a 1147 * symbolic link, then the symbolic link itself, not the target of 1148 * the link, is replaced. </td> 1149 * </tr> 1150 * <tr> 1151 * <td> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </td> 1152 * <td> Attempts to copy the file attributes associated with this file to 1153 * the target file. The exact file attributes that are copied is platform 1154 * and file system dependent and therefore unspecified. Minimally, the 1155 * {@link BasicFileAttributes#lastModifiedTime last-modified-time} is 1156 * copied to the target file if supported by both the source and target 1157 * file store. Copying of file timestamps may result in precision 1158 * loss. </td> 1159 * </tr> 1160 * <tr> 1161 * <td> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </td> 1162 * <td> Symbolic links are not followed. If the file is a symbolic link, 1163 * then the symbolic link itself, not the target of the link, is copied. 1164 * It is implementation specific if file attributes can be copied to the 1165 * new link. In other words, the {@code COPY_ATTRIBUTES} option may be 1166 * ignored when copying a symbolic link. </td> 1167 * </tr> 1168 * </table> 1169 * 1170 * <p> An implementation of this interface may support additional 1171 * implementation specific options. 1172 * 1173 * <p> Copying a file is not an atomic operation. If an {@link IOException} 1174 * is thrown then it possible that the target file is incomplete or some of 1175 * its file attributes have not been copied from the source file. When the 1176 * {@code REPLACE_EXISTING} option is specified and the target file exists, 1177 * then the target file is replaced. The check for the existence of the file 1178 * and the creation of the new file may not be atomic with respect to other 1179 * file system activities. 1180 * 1181 * <p> <b>Usage Example:</b> 1182 * Suppose we want to copy a file into a directory, giving it the same file 1183 * name as the source file: 1184 * <pre> 1185 * Path source = ... 1186 * Path newdir = ... 1187 * Files.copy(source, newdir.resolve(source.getFileName()); 1188 * </pre> 1189 * 1190 * @param source 1191 * the path to the file to copy 1192 * @param target 1193 * the path to the target file (may be associated with a different 1194 * provider to the source path) 1195 * @param options 1196 * options specifying how the copy should be done 1197 * 1198 * @return the path to the target file 1199 * 1200 * @throws UnsupportedOperationException 1201 * if the array contains a copy option that is not supported 1202 * @throws FileAlreadyExistsException 1203 * if the target file exists but cannot be replaced because the 1204 * {@code REPLACE_EXISTING} option is not specified <i>(optional 1205 * specific exception)</i> 1206 * @throws DirectoryNotEmptyException 1207 * the {@code REPLACE_EXISTING} option is specified but the file 1208 * cannot be replaced because it is a non-empty directory 1209 * <i>(optional specific exception)</i> 1210 * @throws IOException 1211 * if an I/O error occurs 1212 * @throws SecurityException 1213 * In the case of the default provider, and a security manager is 1214 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1215 * method is invoked to check read access to the source file, the 1216 * {@link SecurityManager#checkWrite(String) checkWrite} is invoked 1217 * to check write access to the target file. If a symbolic link is 1218 * copied the security manager is invoked to check {@link 1219 * LinkPermission}{@code ("symbolic")}. 1220 */ 1221 public static Path copy(Path source, Path target, CopyOption... options) 1222 throws IOException 1223 { 1224 FileSystemProvider provider = provider(source); 1225 if (provider(target) == provider) { 1226 // same provider 1227 provider.copy(source, target, options); 1228 } else { 1229 // different providers 1230 CopyMoveHelper.copyToForeignTarget(source, target, options); 1231 } 1232 return target; 1233 } 1234 1235 /** 1236 * Move or rename a file to a target file. 1237 * 1238 * <p> By default, this method attempts to move the file to the target 1239 * file, failing if the target file exists except if the source and 1240 * target are the {@link #isSameFile same} file, in which case this method 1241 * has no effect. If the file is a symbolic link then the symbolic link 1242 * itself, not the target of the link, is moved. This method may be 1243 * invoked to move an empty directory. In some implementations a directory 1244 * has entries for special files or links that are created when the 1245 * directory is created. In such implementations a directory is considered 1246 * empty when only the special entries exist. When invoked to move a 1247 * directory that is not empty then the directory is moved if it does not 1248 * require moving the entries in the directory. For example, renaming a 1249 * directory on the same {@link FileStore} will usually not require moving 1250 * the entries in the directory. When moving a directory requires that its 1251 * entries be moved then this method fails (by throwing an {@code 1252 * IOException}). To move a <i>file tree</i> may involve copying rather 1253 * than moving directories and this can be done using the {@link 1254 * #copy copy} method in conjunction with the {@link 1255 * #walkFileTree Files.walkFileTree} utility method. 1256 * 1257 * <p> The {@code options} parameter may include any of the following: 1258 * 1259 * <table border=1 cellpadding=5 summary=""> 1260 * <tr> <th>Option</th> <th>Description</th> </tr> 1261 * <tr> 1262 * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td> 1263 * <td> If the target file exists, then the target file is replaced if it 1264 * is not a non-empty directory. If the target file exists and is a 1265 * symbolic link, then the symbolic link itself, not the target of 1266 * the link, is replaced. </td> 1267 * </tr> 1268 * <tr> 1269 * <td> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </td> 1270 * <td> The move is performed as an atomic file system operation and all 1271 * other options are ignored. If the target file exists then it is 1272 * implementation specific if the existing file is replaced or this method 1273 * fails by throwing an {@link IOException}. If the move cannot be 1274 * performed as an atomic file system operation then {@link 1275 * AtomicMoveNotSupportedException} is thrown. This can arise, for 1276 * example, when the target location is on a different {@code FileStore} 1277 * and would require that the file be copied, or target location is 1278 * associated with a different provider to this object. </td> 1279 * </table> 1280 * 1281 * <p> An implementation of this interface may support additional 1282 * implementation specific options. 1283 * 1284 * <p> Where the move requires that the file be copied then the {@link 1285 * BasicFileAttributes#lastModifiedTime last-modified-time} is copied to the 1286 * new file. An implementation may also attempt to copy other file 1287 * attributes but is not required to fail if the file attributes cannot be 1288 * copied. When the move is performed as a non-atomic operation, and a {@code 1289 * IOException} is thrown, then the state of the files is not defined. The 1290 * original file and the target file may both exist, the target file may be 1291 * incomplete or some of its file attributes may not been copied from the 1292 * original file. 1293 * 1294 * <p> <b>Usage Examples:</b> 1295 * Suppose we want to rename a file to "newname", keeping the file in the 1296 * same directory: 1297 * <pre> 1298 * Path source = ... 1299 * Files.move(source, source.resolveSibling("newname")); 1300 * </pre> 1301 * Alternatively, suppose we want to move a file to new directory, keeping 1302 * the same file name, and replacing any existing file of that name in the 1303 * directory: 1304 * <pre> 1305 * Path source = ... 1306 * Path newdir = ... 1307 * Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING); 1308 * </pre> 1309 * 1310 * @param source 1311 * the path to the file to move 1312 * @param target 1313 * the path to the target file (may be associated with a different 1314 * provider to the source path) 1315 * @param options 1316 * options specifying how the move should be done 1317 * 1318 * @return the path to the target file 1319 * 1320 * @throws UnsupportedOperationException 1321 * if the array contains a copy option that is not supported 1322 * @throws FileAlreadyExistsException 1323 * if the target file exists but cannot be replaced because the 1324 * {@code REPLACE_EXISTING} option is not specified <i>(optional 1325 * specific exception)</i> 1326 * @throws DirectoryNotEmptyException 1327 * the {@code REPLACE_EXISTING} option is specified but the file 1328 * cannot be replaced because it is a non-empty directory 1329 * <i>(optional specific exception)</i> 1330 * @throws AtomicMoveNotSupportedException 1331 * if the options array contains the {@code ATOMIC_MOVE} option but 1332 * the file cannot be moved as an atomic file system operation. 1333 * @throws IOException 1334 * if an I/O error occurs 1335 * @throws SecurityException 1336 * In the case of the default provider, and a security manager is 1337 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 1338 * method is invoked to check write access to both the source and 1339 * target file. 1340 */ 1341 public static Path move(Path source, Path target, CopyOption... options) 1342 throws IOException 1343 { 1344 FileSystemProvider provider = provider(source); 1345 if (provider(target) == provider) { 1346 // same provider 1347 provider.move(source, target, options); 1348 } else { 1349 // different providers 1350 CopyMoveHelper.moveToForeignTarget(source, target, options); 1351 } 1352 return target; 1353 } 1354 1355 // -- Miscellenous -- 1356 1357 /** 1358 * Reads the target of a symbolic link <i>(optional operation)</i>. 1359 * 1360 * <p> If the file system supports <a href="package-summary.html#links">symbolic 1361 * links</a> then this method is used to read the target of the link, failing 1362 * if the file is not a symbolic link. The target of the link need not exist. 1363 * The returned {@code Path} object will be associated with the same file 1364 * system as {@code link}. 1365 * 1366 * @param link 1367 * the path to the symbolic link 1368 * 1369 * @return a {@code Path} object representing the target of the link 1370 * 1371 * @throws UnsupportedOperationException 1372 * if the implementation does not support symbolic links 1373 * @throws NotLinkException 1374 * if the target could otherwise not be read because the file 1375 * is not a symbolic link <i>(optional specific exception)</i> 1376 * @throws IOException 1377 * if an I/O error occurs 1378 * @throws SecurityException 1379 * In the case of the default provider, and a security manager 1380 * is installed, it checks that {@code FilePermission} has been 1381 * granted with the "{@code readlink}" action to read the link. 1382 */ 1383 public static Path readSymbolicLink(Path link) throws IOException { 1384 return provider(link).readSymbolicLink(link); 1385 } 1386 1387 /** 1388 * Returns the {@link FileStore} representing the file store where a file 1389 * is located. 1390 * 1391 * <p> Once a reference to the {@code FileStore} is obtained it is 1392 * implementation specific if operations on the returned {@code FileStore}, 1393 * or {@link FileStoreAttributeView} objects obtained from it, continue 1394 * to depend on the existence of the file. In particular the behavior is not 1395 * defined for the case that the file is deleted or moved to a different 1396 * file store. 1397 * 1398 * @param path 1399 * the path to the file 1400 * 1401 * @return the file store where the file is stored 1402 * 1403 * @throws IOException 1404 * if an I/O error occurs 1405 * @throws SecurityException 1406 * In the case of the default provider, and a security manager is 1407 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1408 * method is invoked to check read access to the file, and in 1409 * addition it checks {@link RuntimePermission}<tt> 1410 * ("getFileStoreAttributes")</tt> 1411 */ 1412 public static FileStore getFileStore(Path path) throws IOException { 1413 return provider(path).getFileStore(path); 1414 } 1415 1416 /** 1417 * Tests if two paths locate the same file. 1418 * 1419 * <p> If both {@code Path} objects are {@link Path#equals(Object) equal} 1420 * then this method returns {@code true} without checking if the file exists. 1421 * If the two {@code Path} objects are associated with different providers 1422 * then this method returns {@code false}. Otherwise, this method checks if 1423 * both {@code Path} objects locate the same file, and depending on the 1424 * implementation, may require to open or access both files. 1425 * 1426 * <p> If the file system and files remain static, then this method implements 1427 * an equivalence relation for non-null {@code Paths}. 1428 * <ul> 1429 * <li>It is <i>reflexive</i>: for {@code Path} {@code f}, 1430 * {@code isSameFile(f,f)} should return {@code true}. 1431 * <li>It is <i>symmetric</i>: for two {@code Paths} {@code f} and {@code g}, 1432 * {@code isSameFile(f,g)} will equal {@code isSameFile(g,f)}. 1433 * <li>It is <i>transitive</i>: for three {@code Paths} 1434 * {@code f}, {@code g}, and {@code h}, if {@code isSameFile(f,g)} returns 1435 * {@code true} and {@code isSameFile(g,h)} returns {@code true}, then 1436 * {@code isSameFile(g,h)} will return return {@code true}. 1437 * </ul> 1438 * 1439 * @param path 1440 * one path to the file 1441 * @param path2 1442 * the other path 1443 * 1444 * @return {@code true} if, and only if, the two paths locate the same file 1445 * 1446 * @throws IOException 1447 * if an I/O error occurs 1448 * @throws SecurityException 1449 * In the case of the default provider, and a security manager is 1450 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1451 * method is invoked to check read access to both files. 1452 * 1453 * @see java.nio.file.attribute.BasicFileAttributes#fileKey 1454 */ 1455 public static boolean isSameFile(Path path, Path path2) throws IOException { 1456 return provider(path).isSameFile(path, path2); 1457 } 1458 1459 /** 1460 * Tells whether or not a file is considered <em>hidden</em>. The exact 1461 * definition of hidden is platform or provider dependent. On UNIX for 1462 * example a file is considered to be hidden if its name begins with a 1463 * period character ('.'). On Windows a file is considered hidden if it 1464 * isn't a directory and the DOS {@link DosFileAttributes#isHidden hidden} 1465 * attribute is set. 1466 * 1467 * <p> Depending on the implementation this method may require to access 1468 * the file system to determine if the file is considered hidden. 1469 * 1470 * @param path 1471 * the path to the file to test 1472 * 1473 * @return {@code true} if the file is considered hidden 1474 * 1475 * @throws IOException 1476 * if an I/O error occurs 1477 * @throws SecurityException 1478 * In the case of the default provider, and a security manager is 1479 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1480 * method is invoked to check read access to the file. 1481 */ 1482 public static boolean isHidden(Path path) throws IOException { 1483 return provider(path).isHidden(path); 1484 } 1485 1486 // lazy loading of default and installed file type detectors 1487 private static class FileTypeDetectors{ 1488 static final FileTypeDetector defaultFileTypeDetector = 1489 sun.nio.fs.DefaultFileTypeDetector.create(); 1490 static final List<FileTypeDetector> installeDetectors = 1491 loadInstalledDetectors(); 1492 1493 // loads all installed file type detectors 1494 private static List<FileTypeDetector> loadInstalledDetectors() { 1495 return AccessController 1496 .doPrivileged(new PrivilegedAction<List<FileTypeDetector>>() { 1497 @Override public List<FileTypeDetector> run() { 1498 List<FileTypeDetector> list = new ArrayList<>(); 1499 ServiceLoader<FileTypeDetector> loader = ServiceLoader 1500 .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader()); 1501 for (FileTypeDetector detector: loader) { 1502 list.add(detector); 1503 } 1504 return list; 1505 }}); 1506 } 1507 } 1508 1509 /** 1510 * Probes the content type of a file. 1511 * 1512 * <p> This method uses the installed {@link FileTypeDetector} implementations 1513 * to probe the given file to determine its content type. Each file type 1514 * detector's {@link FileTypeDetector#probeContentType probeContentType} is 1515 * invoked, in turn, to probe the file type. If the file is recognized then 1516 * the content type is returned. If the file is not recognized by any of the 1517 * installed file type detectors then a system-default file type detector is 1518 * invoked to guess the content type. 1519 * 1520 * <p> A given invocation of the Java virtual machine maintains a system-wide 1521 * list of file type detectors. Installed file type detectors are loaded 1522 * using the service-provider loading facility defined by the {@link ServiceLoader} 1523 * class. Installed file type detectors are loaded using the system class 1524 * loader. If the system class loader cannot be found then the extension class 1525 * loader is used; If the extension class loader cannot be found then the 1526 * bootstrap class loader is used. File type detectors are typically installed 1527 * by placing them in a JAR file on the application class path or in the 1528 * extension directory, the JAR file contains a provider-configuration file 1529 * named {@code java.nio.file.spi.FileTypeDetector} in the resource directory 1530 * {@code META-INF/services}, and the file lists one or more fully-qualified 1531 * names of concrete subclass of {@code FileTypeDetector } that have a zero 1532 * argument constructor. If the process of locating or instantiating the 1533 * installed file type detectors fails then an unspecified error is thrown. 1534 * The ordering that installed providers are located is implementation 1535 * specific. 1536 * 1537 * <p> The return value of this method is the string form of the value of a 1538 * Multipurpose Internet Mail Extension (MIME) content type as 1539 * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: 1540 * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet 1541 * Message Bodies</i></a>. The string is guaranteed to be parsable according 1542 * to the grammar in the RFC. 1543 * 1544 * @param path 1545 * the path to the file to probe 1546 * 1547 * @return The content type of the file, or {@code null} if the content 1548 * type cannot be determined 1549 * 1550 * @throws IOException 1551 * if an I/O error occurs 1552 * @throws SecurityException 1553 * If a security manager is installed and it denies an unspecified 1554 * permission required by a file type detector implementation. 1555 */ 1556 public static String probeContentType(Path path) 1557 throws IOException 1558 { 1559 // try installed file type detectors 1560 for (FileTypeDetector detector: FileTypeDetectors.installeDetectors) { 1561 String result = detector.probeContentType(path); 1562 if (result != null) 1563 return result; 1564 } 1565 1566 // fallback to default 1567 return FileTypeDetectors.defaultFileTypeDetector.probeContentType(path); 1568 } 1569 1570 // -- File Attributes -- 1571 1572 /** 1573 * Returns a file attribute view of a given type. 1574 * 1575 * <p> A file attribute view provides a read-only or updatable view of a 1576 * set of file attributes. This method is intended to be used where the file 1577 * attribute view defines type-safe methods to read or update the file 1578 * attributes. The {@code type} parameter is the type of the attribute view 1579 * required and the method returns an instance of that type if supported. 1580 * The {@link BasicFileAttributeView} type supports access to the basic 1581 * attributes of a file. Invoking this method to select a file attribute 1582 * view of that type will always return an instance of that class. 1583 * 1584 * <p> The {@code options} array may be used to indicate how symbolic links 1585 * are handled by the resulting file attribute view for the case that the 1586 * file is a symbolic link. By default, symbolic links are followed. If the 1587 * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then 1588 * symbolic links are not followed. This option is ignored by implementations 1589 * that do not support symbolic links. 1590 * 1591 * <p> <b>Usage Example:</b> 1592 * Suppose we want read or set a file's ACL, if supported: 1593 * <pre> 1594 * Path path = ... 1595 * AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); 1596 * if (view != null) { 1597 * List<AclEntry> acl = view.getAcl(); 1598 * : 1599 * } 1600 * </pre> 1601 * 1602 * 1603 * @param path 1604 * the path to the file 1605 * @param type 1606 * the {@code Class} object corresponding to the file attribute view 1607 * @param options 1608 * options indicating how symbolic links are handled 1609 * 1610 * @return a file attribute view of the specified type, or {@code null} if 1611 * the attribute view type is not available 1612 */ 1613 public static <V extends FileAttributeView> V getFileAttributeView(Path path, 1614 Class<V> type, 1615 LinkOption... options) 1616 { 1617 return provider(path).getFileAttributeView(path, type, options); 1618 } 1619 1620 /** 1621 * Reads a file's attributes as a bulk operation. 1622 * 1623 * <p> The {@code type} parameter is the type of the attributes required 1624 * and this method returns an instance of that type if supported. All 1625 * implementations support a basic set of file attributes and so invoking 1626 * this method with a {@code type} parameter of {@code 1627 * BasicFileAttributes.class} will not throw {@code 1628 * UnsupportedOperationException}. 1629 * 1630 * <p> The {@code options} array may be used to indicate how symbolic links 1631 * are handled for the case that the file is a symbolic link. By default, 1632 * symbolic links are followed and the file attribute of the final target 1633 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1634 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1635 * 1636 * <p> It is implementation specific if all file attributes are read as an 1637 * atomic operation with respect to other file system operations. 1638 * 1639 * <p> <b>Usage Example:</b> 1640 * Suppose we want to read a file's attributes in bulk: 1641 * <pre> 1642 * Path path = ... 1643 * BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 1644 * </pre> 1645 * Alternatively, suppose we want to read file's POSIX attributes without 1646 * following symbolic links: 1647 * <pre> 1648 * PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS); 1649 * </pre> 1650 * 1651 * @param path 1652 * the path to the file 1653 * @param type 1654 * the {@code Class} of the file attributes required 1655 * to read 1656 * @param options 1657 * options indicating how symbolic links are handled 1658 * 1659 * @return the file attributes 1660 * 1661 * @throws UnsupportedOperationException 1662 * if an attributes of the given type are not supported 1663 * @throws IOException 1664 * if an I/O error occurs 1665 * @throws SecurityException 1666 * In the case of the default provider, a security manager is 1667 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1668 * method is invoked to check read access to the file. If this 1669 * method is invoked to read security sensitive attributes then the 1670 * security manager may be invoke to check for additional permissions. 1671 */ 1672 public static <A extends BasicFileAttributes> A readAttributes(Path path, 1673 Class<A> type, 1674 LinkOption... options) 1675 throws IOException 1676 { 1677 return provider(path).readAttributes(path, type, options); 1678 } 1679 1680 /** 1681 * Sets the value of a file attribute. 1682 * 1683 * <p> The {@code attribute} parameter identifies the attribute to be set 1684 * and takes the form: 1685 * <blockquote> 1686 * [<i>view-name</i><b>:</b>]<i>attribute-name</i> 1687 * </blockquote> 1688 * where square brackets [...] delineate an optional component and the 1689 * character {@code ':'} stands for itself. 1690 * 1691 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1692 * FileAttributeView} that identifies a set of file attributes. If not 1693 * specified then it defaults to {@code "basic"}, the name of the file 1694 * attribute view that identifies the basic set of file attributes common to 1695 * many file systems. <i>attribute-name</i> is the name of the attribute 1696 * within the set. 1697 * 1698 * <p> The {@code options} array may be used to indicate how symbolic links 1699 * are handled for the case that the file is a symbolic link. By default, 1700 * symbolic links are followed and the file attribute of the final target 1701 * of the link is set. If the option {@link LinkOption#NOFOLLOW_LINKS 1702 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1703 * 1704 * <p> <b>Usage Example:</b> 1705 * Suppose we want to set the DOS "hidden" attribute: 1706 * <pre> 1707 * Path path = ... 1708 * Files.setAttribute(path, "dos:hidden", true); 1709 * </pre> 1710 * 1711 * @param path 1712 * the path to the file 1713 * @param attribute 1714 * the attribute to set 1715 * @param value 1716 * the attribute value 1717 * @param options 1718 * options indicating how symbolic links are handled 1719 * 1720 * @return the {@code path} parameter 1721 * 1722 * @throws UnsupportedOperationException 1723 * if the attribute view is not available 1724 * @throws IllegalArgumentException 1725 * if the attribute name is not specified, or is not recognized, or 1726 * the attribute value is of the correct type but has an 1727 * inappropriate value 1728 * @throws ClassCastException 1729 * if the attribute value is not of the expected type or is a 1730 * collection containing elements that are not of the expected 1731 * type 1732 * @throws IOException 1733 * if an I/O error occurs 1734 * @throws SecurityException 1735 * In the case of the default provider, and a security manager is 1736 * installed, its {@link SecurityManager#checkWrite(String) checkWrite} 1737 * method denies write access to the file. If this method is invoked 1738 * to set security sensitive attributes then the security manager 1739 * may be invoked to check for additional permissions. 1740 */ 1741 public static Path setAttribute(Path path, String attribute, Object value, 1742 LinkOption... options) 1743 throws IOException 1744 { 1745 provider(path).setAttribute(path, attribute, value, options); 1746 return path; 1747 } 1748 1749 /** 1750 * Reads the value of a file attribute. 1751 * 1752 * <p> The {@code attribute} parameter identifies the attribute to be read 1753 * and takes the form: 1754 * <blockquote> 1755 * [<i>view-name</i><b>:</b>]<i>attribute-name</i> 1756 * </blockquote> 1757 * where square brackets [...] delineate an optional component and the 1758 * character {@code ':'} stands for itself. 1759 * 1760 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1761 * FileAttributeView} that identifies a set of file attributes. If not 1762 * specified then it defaults to {@code "basic"}, the name of the file 1763 * attribute view that identifies the basic set of file attributes common to 1764 * many file systems. <i>attribute-name</i> is the name of the attribute. 1765 * 1766 * <p> The {@code options} array may be used to indicate how symbolic links 1767 * are handled for the case that the file is a symbolic link. By default, 1768 * symbolic links are followed and the file attribute of the final target 1769 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1770 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1771 * 1772 * <p> <b>Usage Example:</b> 1773 * Suppose we require the user ID of the file owner on a system that 1774 * supports a "{@code unix}" view: 1775 * <pre> 1776 * Path path = ... 1777 * int uid = (Integer)Files.getAttribute(path, "unix:uid"); 1778 * </pre> 1779 * 1780 * @param path 1781 * the path to the file 1782 * @param attribute 1783 * the attribute to read 1784 * @param options 1785 * options indicating how symbolic links are handled 1786 * 1787 * @return the attribute value 1788 * 1789 * @throws UnsupportedOperationException 1790 * if the attribute view is not available 1791 * @throws IllegalArgumentException 1792 * if the attribute name is not specified or is not recognized 1793 * @throws IOException 1794 * if an I/O error occurs 1795 * @throws SecurityException 1796 * In the case of the default provider, and a security manager is 1797 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1798 * method denies read access to the file. If this method is invoked 1799 * to read security sensitive attributes then the security manager 1800 * may be invoked to check for additional permissions. 1801 */ 1802 public static Object getAttribute(Path path, String attribute, 1803 LinkOption... options) 1804 throws IOException 1805 { 1806 // only one attribute should be read 1807 if (attribute.indexOf('*') >= 0 || attribute.indexOf(',') >= 0) 1808 throw new IllegalArgumentException(attribute); 1809 Map<String,Object> map = readAttributes(path, attribute, options); 1810 assert map.size() == 1; 1811 String name; 1812 int pos = attribute.indexOf(':'); 1813 if (pos == -1) { 1814 name = attribute; 1815 } else { 1816 name = (pos == attribute.length()) ? "" : attribute.substring(pos+1); 1817 } 1818 return map.get(name); 1819 } 1820 1821 /** 1822 * Reads a set of file attributes as a bulk operation. 1823 * 1824 * <p> The {@code attributes} parameter identifies the attributes to be read 1825 * and takes the form: 1826 * <blockquote> 1827 * [<i>view-name</i><b>:</b>]<i>attribute-list</i> 1828 * </blockquote> 1829 * where square brackets [...] delineate an optional component and the 1830 * character {@code ':'} stands for itself. 1831 * 1832 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1833 * FileAttributeView} that identifies a set of file attributes. If not 1834 * specified then it defaults to {@code "basic"}, the name of the file 1835 * attribute view that identifies the basic set of file attributes common to 1836 * many file systems. 1837 * 1838 * <p> The <i>attribute-list</i> component is a comma separated list of 1839 * zero or more names of attributes to read. If the list contains the value 1840 * {@code "*"} then all attributes are read. Attributes that are not supported 1841 * are ignored and will not be present in the returned map. It is 1842 * implementation specific if all attributes are read as an atomic operation 1843 * with respect to other file system operations. 1844 * 1845 * <p> The following examples demonstrate possible values for the {@code 1846 * attributes} parameter: 1847 * 1848 * <blockquote> 1849 * <table border="0"> 1850 * <tr> 1851 * <td> {@code "*"} </td> 1852 * <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td> 1853 * </tr> 1854 * <tr> 1855 * <td> {@code "size,lastModifiedTime,lastAccessTime"} </td> 1856 * <td> Reads the file size, last modified time, and last access time 1857 * attributes. </td> 1858 * </tr> 1859 * <tr> 1860 * <td> {@code "posix:*"} </td> 1861 * <td> Read all {@link PosixFileAttributes POSIX-file-attributes}. </td> 1862 * </tr> 1863 * <tr> 1864 * <td> {@code "posix:permissions,owner,size"} </td> 1865 * <td> Reads the POSX file permissions, owner, and file size. </td> 1866 * </tr> 1867 * </table> 1868 * </blockquote> 1869 * 1870 * <p> The {@code options} array may be used to indicate how symbolic links 1871 * are handled for the case that the file is a symbolic link. By default, 1872 * symbolic links are followed and the file attribute of the final target 1873 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1874 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1875 * 1876 * @param path 1877 * the path to the file 1878 * @param attributes 1879 * the attributes to read 1880 * @param options 1881 * options indicating how symbolic links are handled 1882 * 1883 * @return a map of the attributes returned; The map's keys are the 1884 * attribute names, its values are the attribute values 1885 * 1886 * @throws UnsupportedOperationException 1887 * if the attribute view is not available 1888 * @throws IllegalArgumentException 1889 * if no attributes are specified or an unrecognized attributes is 1890 * specified 1891 * @throws IOException 1892 * if an I/O error occurs 1893 * @throws SecurityException 1894 * In the case of the default provider, and a security manager is 1895 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1896 * method denies read access to the file. If this method is invoked 1897 * to read security sensitive attributes then the security manager 1898 * may be invoke to check for additional permissions. 1899 */ 1900 public static Map<String,Object> readAttributes(Path path, String attributes, 1901 LinkOption... options) 1902 throws IOException 1903 { 1904 return provider(path).readAttributes(path, attributes, options); 1905 } 1906 1907 /** 1908 * Returns a file's POSIX file permissions. 1909 * 1910 * <p> The {@code path} parameter is associated with a {@code FileSystem} 1911 * that supports the {@link PosixFileAttributeView}. This attribute view 1912 * provides access to file attributes commonly associated with files on file 1913 * systems used by operating systems that implement the Portable Operating 1914 * System Interface (POSIX) family of standards. 1915 * 1916 * <p> The {@code options} array may be used to indicate how symbolic links 1917 * are handled for the case that the file is a symbolic link. By default, 1918 * symbolic links are followed and the file attribute of the final target 1919 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1920 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1921 * 1922 * @param path 1923 * the path to the file 1924 * @param options 1925 * options indicating how symbolic links are handled 1926 * 1927 * @return the file permissions 1928 * 1929 * @throws UnsupportedOperationException 1930 * if the associated file system does not support the {@code 1931 * PosixFileAttributeView} 1932 * @throws IOException 1933 * if an I/O error occurs 1934 * @throws SecurityException 1935 * In the case of the default provider, a security manager is 1936 * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> 1937 * or its {@link SecurityManager#checkRead(String) checkRead} method 1938 * denies read access to the file. 1939 */ 1940 public static Set<PosixFilePermission> getPosixFilePermissions(Path path, 1941 LinkOption... options) 1942 throws IOException 1943 { 1944 return readAttributes(path, PosixFileAttributes.class, options).permissions(); 1945 } 1946 1947 /** 1948 * Sets a file's POSIX permissions. 1949 * 1950 * <p> The {@code path} parameter is associated with a {@code FileSystem} 1951 * that supports the {@link PosixFileAttributeView}. This attribute view 1952 * provides access to file attributes commonly associated with files on file 1953 * systems used by operating systems that implement the Portable Operating 1954 * System Interface (POSIX) family of standards. 1955 * 1956 * @param path 1957 * A file reference that locates the file 1958 * @param perms 1959 * The new set of permissions 1960 * 1961 * @throws UnsupportedOperationException 1962 * if the associated file system does not support the {@code 1963 * PosixFileAttributeView} 1964 * @throws ClassCastException 1965 * if the sets contains elements that are not of type {@code 1966 * PosixFilePermission} 1967 * @throws IOException 1968 * if an I/O error occurs 1969 * @throws SecurityException 1970 * In the case of the default provider, and a security manager is 1971 * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> 1972 * or its {@link SecurityManager#checkWrite(String) checkWrite} 1973 * method denies write access to the file. 1974 */ 1975 public static Path setPosixFilePermissions(Path path, 1976 Set<PosixFilePermission> perms) 1977 throws IOException 1978 { 1979 PosixFileAttributeView view = 1980 getFileAttributeView(path, PosixFileAttributeView.class); 1981 if (view == null) 1982 throw new UnsupportedOperationException(); 1983 view.setPermissions(perms); 1984 return path; 1985 } 1986 1987 /** 1988 * Returns the owner of a file. 1989 * 1990 * <p> The {@code path} parameter is associated with a file system that 1991 * supports {@link FileOwnerAttributeView}. This file attribute view provides 1992 * access to a file attribute that is the owner of the file. 1993 * 1994 * @param path 1995 * A file reference that locates the file 1996 * @param options 1997 * options indicating how symbolic links are handled 1998 * 1999 * @return A user principal representing the owner of the file 2000 * 2001 * @throws UnsupportedOperationException 2002 * if the associated file system does not support the {@code 2003 * FileOwnerAttributeView} 2004 * @throws IOException 2005 * if an I/O error occurs 2006 * @throws SecurityException 2007 * In the case of the default provider, and a security manager is 2008 * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> 2009 * or its {@link SecurityManager#checkRead(String) checkRead} method 2010 * denies read access to the file. 2011 */ 2012 public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException { 2013 FileOwnerAttributeView view = 2014 getFileAttributeView(path, FileOwnerAttributeView.class, options); 2015 if (view == null) 2016 throw new UnsupportedOperationException(); 2017 return view.getOwner(); 2018 } 2019 2020 /** 2021 * Updates the file owner. 2022 * 2023 * <p> The {@code path} parameter is associated with a file system that 2024 * supports {@link FileOwnerAttributeView}. This file attribute view provides 2025 * access to a file attribute that is the owner of the file. 2026 * 2027 * <p> <b>Usage Example:</b> 2028 * Suppose we want to make "joe" the owner of a file: 2029 * <pre> 2030 * Path path = ... 2031 * UserPrincipalLookupService lookupService = 2032 * provider(path).getUserPrincipalLookupService(); 2033 * UserPrincipal joe = lookupService.lookupPrincipalByName("joe"); 2034 * Files.setOwner(path, joe); 2035 * </pre> 2036 * 2037 * @param path 2038 * A file reference that locates the file 2039 * @param owner 2040 * The new file owner 2041 * 2042 * @throws UnsupportedOperationException 2043 * if the associated file system does not support the {@code 2044 * FileOwnerAttributeView} 2045 * @throws IOException 2046 * if an I/O error occurs 2047 * @throws SecurityException 2048 * In the case of the default provider, and a security manager is 2049 * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> 2050 * or its {@link SecurityManager#checkWrite(String) checkWrite} 2051 * method denies write access to the file. 2052 * 2053 * @see FileSystem#getUserPrincipalLookupService 2054 * @see java.nio.file.attribute.UserPrincipalLookupService 2055 */ 2056 public static Path setOwner(Path path, UserPrincipal owner) 2057 throws IOException 2058 { 2059 FileOwnerAttributeView view = 2060 getFileAttributeView(path, FileOwnerAttributeView.class); 2061 if (view == null) 2062 throw new UnsupportedOperationException(); 2063 view.setOwner(owner); 2064 return path; 2065 } 2066 2067 /** 2068 * Tests whether a file is a symbolic link. 2069 * 2070 * <p> Where is it required to distinguish an I/O exception from the case 2071 * that the file is not a symbolic link then the file attributes can be 2072 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2073 * readAttributes} method and the file type tested with the {@link 2074 * BasicFileAttributes#isSymbolicLink} method. 2075 * 2076 * @return {@code true} if the file is a symbolic link; {@code false} if 2077 * the file does not exist, is not a symbolic link, or it cannot 2078 * be determined if the file is a symbolic link or not. 2079 * 2080 * @throws SecurityException 2081 * In the case of the default provider, and a security manager is 2082 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2083 * method denies read access to the file. 2084 */ 2085 public static boolean isSymbolicLink(Path path) { 2086 try { 2087 return readAttributes(path, 2088 BasicFileAttributes.class, 2089 LinkOption.NOFOLLOW_LINKS).isSymbolicLink(); 2090 } catch (IOException ioe) { 2091 return false; 2092 } 2093 } 2094 2095 /** 2096 * Tests whether a file is a directory. 2097 * 2098 * <p> The {@code options} array may be used to indicate how symbolic links 2099 * are handled for the case that the file is a symbolic link. By default, 2100 * symbolic links are followed and the file attribute of the final target 2101 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2102 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2103 * 2104 * <p> Where is it required to distinguish an I/O exception from the case 2105 * that the file is not a directory then the file attributes can be 2106 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2107 * readAttributes} method and the file type tested with the {@link 2108 * BasicFileAttributes#isDirectory} method. 2109 * 2110 * @param path 2111 * the path to the file to test 2112 * @param options 2113 * options indicating how symbolic links are handled 2114 * 2115 * @return {@code true} if the file is a directory; {@code false} if 2116 * the file does not exist, is not a directory, or it cannot 2117 * be determined if the file is a directory or not. 2118 * 2119 * @throws SecurityException 2120 * In the case of the default provider, and a security manager is 2121 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2122 * method denies read access to the file. 2123 */ 2124 public static boolean isDirectory(Path path, LinkOption... options) { 2125 try { 2126 return readAttributes(path, BasicFileAttributes.class, options).isDirectory(); 2127 } catch (IOException ioe) { 2128 return false; 2129 } 2130 } 2131 2132 /** 2133 * Tests whether a file is a regular file with opaque content. 2134 * 2135 * <p> The {@code options} array may be used to indicate how symbolic links 2136 * are handled for the case that the file is a symbolic link. By default, 2137 * symbolic links are followed and the file attribute of the final target 2138 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2139 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2140 * 2141 * <p> Where is it required to distinguish an I/O exception from the case 2142 * that the file is not a regular file then the file attributes can be 2143 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2144 * readAttributes} method and the file type tested with the {@link 2145 * BasicFileAttributes#isRegularFile} method. 2146 * 2147 * @param path 2148 * the path to the file 2149 * @param options 2150 * options indicating how symbolic links are handled 2151 * 2152 * @return {@code true} if the file is a regular file; {@code false} if 2153 * the file does not exist, is not a regular file, or it 2154 * cannot be determined if the file is a regular file or not. 2155 * 2156 * @throws SecurityException 2157 * In the case of the default provider, and a security manager is 2158 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2159 * method denies read access to the file. 2160 */ 2161 public static boolean isRegularFile(Path path, LinkOption... options) { 2162 try { 2163 return readAttributes(path, BasicFileAttributes.class, options).isRegularFile(); 2164 } catch (IOException ioe) { 2165 return false; 2166 } 2167 } 2168 2169 /** 2170 * Returns a file's last modified time. 2171 * 2172 * <p> The {@code options} array may be used to indicate how symbolic links 2173 * are handled for the case that the file is a symbolic link. By default, 2174 * symbolic links are followed and the file attribute of the final target 2175 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2176 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2177 * 2178 * @param path 2179 * the path to the file 2180 * @param options 2181 * options indicating how symbolic links are handled 2182 * 2183 * @return a {@code FileTime} representing the time the file was last 2184 * modified, or an implementation specific default when a time 2185 * stamp to indicate the time of last modification is not supported 2186 * by the file system 2187 * 2188 * @throws IOException 2189 * if an I/O error occurs 2190 * @throws SecurityException 2191 * In the case of the default provider, and a security manager is 2192 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2193 * method denies read access to the file. 2194 * 2195 * @see BasicFileAttributes#lastModifiedTime 2196 */ 2197 public static FileTime getLastModifiedTime(Path path, LinkOption... options) 2198 throws IOException 2199 { 2200 return readAttributes(path, BasicFileAttributes.class, options).lastModifiedTime(); 2201 } 2202 2203 /** 2204 * Updates a file's last modified time attribute. The file time is converted 2205 * to the epoch and precision supported by the file system. Converting from 2206 * finer to coarser granularities result in precision loss. The behavior of 2207 * this method when attempting to set the last modified time when it is not 2208 * supported by the file system or is outside the range supported by the 2209 * underlying file store is not defined. It may or not fail by throwing an 2210 * {@code IOException}. 2211 * 2212 * <p> <b>Usage Example:</b> 2213 * Suppose we want to set the last modified time to the current time: 2214 * <pre> 2215 * Path path = ... 2216 * FileTime now = FileTime.fromMillis(System.currentTimeMillis()); 2217 * Files.setLastModifiedTime(path, now); 2218 * </pre> 2219 * 2220 * @param path 2221 * the path to the file 2222 * @param time 2223 * the new last modified time 2224 * 2225 * @return the file 2226 * 2227 * @throws IOException 2228 * if an I/O error occurs 2229 * @throws SecurityException 2230 * In the case of the default provider, the security manager's {@link 2231 * SecurityManager#checkWrite(String) checkWrite} method is invoked 2232 * to check write access to file 2233 * 2234 * @see BasicFileAttributeView#setTimes 2235 */ 2236 public static Path setLastModifiedTime(Path path, FileTime time) 2237 throws IOException 2238 { 2239 getFileAttributeView(path, BasicFileAttributeView.class) 2240 .setTimes(time, null, null); 2241 return path; 2242 } 2243 2244 /** 2245 * Returns the size of a file (in bytes). The size may differ from the 2246 * actual size on the file system due to compression, support for sparse 2247 * files, or other reasons. The size of files that are not {@link 2248 * #isRegularFile regular} files is implementation specific and 2249 * therefore unspecified. 2250 * 2251 * @param path 2252 * the path to the file 2253 * 2254 * @return the file size, in bytes 2255 * 2256 * @throws IOException 2257 * if an I/O error occurs 2258 * @throws SecurityException 2259 * In the case of the default provider, and a security manager is 2260 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2261 * method denies read access to the file. 2262 * 2263 * @see BasicFileAttributes#size 2264 */ 2265 public static long size(Path path) throws IOException { 2266 return readAttributes(path, BasicFileAttributes.class).size(); 2267 } 2268 2269 // -- Accessibility -- 2270 2271 /** 2272 * Returns {@code false} if NOFOLLOW_LINKS is present. 2273 */ 2274 private static boolean followLinks(LinkOption... options) { 2275 boolean followLinks = true; 2276 for (LinkOption opt: options) { 2277 if (opt == LinkOption.NOFOLLOW_LINKS) { 2278 followLinks = false; 2279 continue; 2280 } 2281 if (opt == null) 2282 throw new NullPointerException(); 2283 throw new AssertionError("Should not get here"); 2284 } 2285 return followLinks; 2286 } 2287 2288 /** 2289 * Tests whether a file exists. 2290 * 2291 * <p> The {@code options} parameter may be used to indicate how symbolic links 2292 * are handled for the case that the file is a symbolic link. By default, 2293 * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS 2294 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2295 * 2296 * <p> Note that the result of this method is immediately outdated. If this 2297 * method indicates the file exists then there is no guarantee that a 2298 * subsequence access will succeed. Care should be taken when using this 2299 * method in security sensitive applications. 2300 * 2301 * @param path 2302 * the path to the file to test 2303 * @param options 2304 * options indicating how symbolic links are handled 2305 * . 2306 * @return {@code true} if the file exists; {@code false} if the file does 2307 * not exist or its existence cannot be determined. 2308 * 2309 * @throws SecurityException 2310 * In the case of the default provider, the {@link 2311 * SecurityManager#checkRead(String)} is invoked to check 2312 * read access to the file. 2313 * 2314 * @see #notExists 2315 */ 2316 public static boolean exists(Path path, LinkOption... options) { 2317 try { 2318 if (followLinks(options)) { 2319 provider(path).checkAccess(path); 2320 } else { 2321 // attempt to read attributes without following links 2322 readAttributes(path, BasicFileAttributes.class, 2323 LinkOption.NOFOLLOW_LINKS); 2324 } 2325 // file exists 2326 return true; 2327 } catch (IOException x) { 2328 // does not exist or unable to determine if file exists 2329 return false; 2330 } 2331 2332 } 2333 2334 /** 2335 * Tests whether the file located by this path does not exist. This method 2336 * is intended for cases where it is required to take action when it can be 2337 * confirmed that a file does not exist. 2338 * 2339 * <p> The {@code options} parameter may be used to indicate how symbolic links 2340 * are handled for the case that the file is a symbolic link. By default, 2341 * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS 2342 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2343 * 2344 * <p> Note that this method is not the complement of the {@link #exists 2345 * exists} method. Where it is not possible to determine if a file exists 2346 * or not then both methods return {@code false}. As with the {@code exists} 2347 * method, the result of this method is immediately outdated. If this 2348 * method indicates the file does exist then there is no guarantee that a 2349 * subsequence attempt to create the file will succeed. Care should be taken 2350 * when using this method in security sensitive applications. 2351 * 2352 * @param path 2353 * the path to the file to test 2354 * @param options 2355 * options indicating how symbolic links are handled 2356 * 2357 * @return {@code true} if the file does not exist; {@code false} if the 2358 * file exists or its existence cannot be determined 2359 * 2360 * @throws SecurityException 2361 * In the case of the default provider, the {@link 2362 * SecurityManager#checkRead(String)} is invoked to check 2363 * read access to the file. 2364 */ 2365 public static boolean notExists(Path path, LinkOption... options) { 2366 try { 2367 if (followLinks(options)) { 2368 provider(path).checkAccess(path); 2369 } else { 2370 // attempt to read attributes without following links 2371 readAttributes(path, BasicFileAttributes.class, 2372 LinkOption.NOFOLLOW_LINKS); 2373 } 2374 // file exists 2375 return false; 2376 } catch (NoSuchFileException x) { 2377 // file confirmed not to exist 2378 return true; 2379 } catch (IOException x) { 2380 return false; 2381 } 2382 } 2383 2384 /** 2385 * Used by isReadbale, isWritable, isExecutable to test access to a file. 2386 */ 2387 private static boolean isAccessible(Path path, AccessMode... modes) { 2388 try { 2389 provider(path).checkAccess(path, modes); 2390 return true; 2391 } catch (IOException x) { 2392 return false; 2393 } 2394 } 2395 2396 /** 2397 * Tests whether a file is readable. This method checks that a file exists 2398 * and that this Java virtual machine has appropriate privileges that would 2399 * allow it open the file for reading. Depending on the implementation, this 2400 * method may require to read file permissions, access control lists, or 2401 * other file attributes in order to check the effective access to the file. 2402 * Consequently, this method may not be atomic with respect to other file 2403 * system operations. 2404 * 2405 * <p> Note that the result of this method is immediately outdated, there is 2406 * no guarantee that a subsequent attempt to open the file for reading will 2407 * succeed (or even that it will access the same file). Care should be taken 2408 * when using this method in security sensitive applications. 2409 * 2410 * @param path 2411 * the path to the file to check 2412 * 2413 * @return {@code true} if the file exists and is readable; {@code false} 2414 * if the file does not exist, read access would be denied because 2415 * the Java virtual machine has insufficient privileges, or access 2416 * cannot be determined 2417 * 2418 * @throws SecurityException 2419 * In the case of the default provider, and a security manager is 2420 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2421 * is invoked to check read access to the file. 2422 */ 2423 public static boolean isReadable(Path path) { 2424 return isAccessible(path, AccessMode.READ); 2425 } 2426 2427 /** 2428 * Tests whether a file is writable. This method checks that a file exists 2429 * and that this Java virtual machine has appropriate privileges that would 2430 * allow it open the file for writing. Depending on the implementation, this 2431 * method may require to read file permissions, access control lists, or 2432 * other file attributes in order to check the effective access to the file. 2433 * Consequently, this method may not be atomic with respect to other file 2434 * system operations. 2435 * 2436 * <p> Note that result of this method is immediately outdated, there is no 2437 * guarantee that a subsequent attempt to open the file for writing will 2438 * succeed (or even that it will access the same file). Care should be taken 2439 * when using this method in security sensitive applications. 2440 * 2441 * @param path 2442 * the path to the file to check 2443 * 2444 * @return {@code true} if the file exists and is writable; {@code false} 2445 * if the file does not exist, write access would be denied because 2446 * the Java virtual machine has insufficient privileges, or access 2447 * cannot be determined 2448 * 2449 * @throws SecurityException 2450 * In the case of the default provider, and a security manager is 2451 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2452 * is invoked to check write access to the file. 2453 */ 2454 public static boolean isWritable(Path path) { 2455 return isAccessible(path, AccessMode.WRITE); 2456 } 2457 2458 /** 2459 * Tests whether a file is executable. This method checks that a file exists 2460 * and that this Java virtual machine has appropriate privileges to {@link 2461 * Runtime#exec execute} the file. The semantics may differ when checking 2462 * access to a directory. For example, on UNIX systems, checking for 2463 * execute access checks that the Java virtual machine has permission to 2464 * search the directory in order to access file or subdirectories. 2465 * 2466 * <p> Depending on the implementation, this method may require to read file 2467 * permissions, access control lists, or other file attributes in order to 2468 * check the effective access to the file. Consequently, this method may not 2469 * be atomic with respect to other file system operations. 2470 * 2471 * <p> Note that the result of this method is immediately outdated, there is 2472 * no guarantee that a subsequent attempt to execute the file will succeed 2473 * (or even that it will access the same file). Care should be taken when 2474 * using this method in security sensitive applications. 2475 * 2476 * @param path 2477 * the path to the file to check 2478 * 2479 * @return {@code true} if the file exists and is executable; {@code false} 2480 * if the file does not exist, execute access would be denied because 2481 * the Java virtual machine has insufficient privileges, or access 2482 * cannot be determined 2483 * 2484 * @throws SecurityException 2485 * In the case of the default provider, and a security manager is 2486 * installed, the {@link SecurityManager#checkExec(String) 2487 * checkExec} is invoked to check execute access to the file. 2488 */ 2489 public static boolean isExecutable(Path path) { 2490 return isAccessible(path, AccessMode.EXECUTE); 2491 } 2492 2493 // -- Recursive operations -- 2494 2495 /** 2496 * Walks a file tree. 2497 * 2498 * <p> This method walks a file tree rooted at a given starting file. The 2499 * file tree traversal is <em>depth-first</em> with the given {@link 2500 * FileVisitor} invoked for each file encountered. File tree traversal 2501 * completes when all accessible files in the tree have been visited, or a 2502 * visit method returns a result of {@link FileVisitResult#TERMINATE 2503 * TERMINATE}. Where a visit method terminates due an {@code IOException}, 2504 * an uncaught error, or runtime exception, then the traversal is terminated 2505 * and the error or exception is propagated to the caller of this method. 2506 * 2507 * <p> For each file encountered this method attempts to read its {@link 2508 * java.nio.file.attribute.BasicFileAttributes}. If the file is not a 2509 * directory then the {@link FileVisitor#visitFile visitFile} method is 2510 * invoked with the file attributes. If the file attributes cannot be read, 2511 * due to an I/O exception, then the {@link FileVisitor#visitFileFailed 2512 * visitFileFailed} method is invoked with the I/O exception. 2513 * 2514 * <p> Where the file is a directory, and the directory could not be opened, 2515 * then the {@code visitFileFailed} method is invoked with the I/O exception, 2516 * after which, the file tree walk continues, by default, at the next 2517 * <em>sibling</em> of the directory. 2518 * 2519 * <p> Where the directory is opened successfully, then the entries in the 2520 * directory, and their <em>descendants</em> are visited. When all entries 2521 * have been visited, or an I/O error occurs during iteration of the 2522 * directory, then the directory is closed and the visitor's {@link 2523 * FileVisitor#postVisitDirectory postVisitDirectory} method is invoked. 2524 * The file tree walk then continues, by default, at the next <em>sibling</em> 2525 * of the directory. 2526 * 2527 * <p> By default, symbolic links are not automatically followed by this 2528 * method. If the {@code options} parameter contains the {@link 2529 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are 2530 * followed. When following links, and the attributes of the target cannot 2531 * be read, then this method attempts to get the {@code BasicFileAttributes} 2532 * of the link. If they can be read then the {@code visitFile} method is 2533 * invoked with the attributes of the link (otherwise the {@code visitFileFailed} 2534 * method is invoked as specified above). 2535 * 2536 * <p> If the {@code options} parameter contains the {@link 2537 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps 2538 * track of directories visited so that cycles can be detected. A cycle 2539 * arises when there is an entry in a directory that is an ancestor of the 2540 * directory. Cycle detection is done by recording the {@link 2541 * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, 2542 * or if file keys are not available, by invoking the {@link #isSameFile 2543 * isSameFile} method to test if a directory is the same file as an 2544 * ancestor. When a cycle is detected it is treated as an I/O error, and the 2545 * {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with 2546 * an instance of {@link FileSystemLoopException}. 2547 * 2548 * <p> The {@code maxDepth} parameter is the maximum number of levels of 2549 * directories to visit. A value of {@code 0} means that only the starting 2550 * file is visited, unless denied by the security manager. A value of 2551 * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all 2552 * levels should be visited. The {@code visitFile} method is invoked for all 2553 * files, including directories, encountered at {@code maxDepth}, unless the 2554 * basic file attributes cannot be read, in which case the {@code 2555 * visitFileFailed} method is invoked. 2556 * 2557 * <p> If a visitor returns a result of {@code null} then {@code 2558 * NullPointerException} is thrown. 2559 * 2560 * <p> When a security manager is installed and it denies access to a file 2561 * (or directory), then it is ignored and the visitor is not invoked for 2562 * that file (or directory). 2563 * 2564 * @param start 2565 * the starting file 2566 * @param options 2567 * options to configure the traversal 2568 * @param maxDepth 2569 * the maximum number of directory levels to visit 2570 * @param visitor 2571 * the file visitor to invoke for each file 2572 * 2573 * @return the starting file 2574 * 2575 * @throws IllegalArgumentException 2576 * if the {@code maxDepth} parameter is negative 2577 * @throws SecurityException 2578 * If the security manager denies access to the starting file. 2579 * In the case of the default provider, the {@link 2580 * SecurityManager#checkRead(String) checkRead} method is invoked 2581 * to check read access to the directory. 2582 * @throws IOException 2583 * if an I/O error is thrown by a visitor method 2584 */ 2585 public static Path walkFileTree(Path start, 2586 Set<FileVisitOption> options, 2587 int maxDepth, 2588 FileVisitor<? super Path> visitor) 2589 throws IOException 2590 { 2591 if (maxDepth < 0) 2592 throw new IllegalArgumentException("'maxDepth' is negative"); 2593 new FileTreeWalker(options, visitor, maxDepth).walk(start); 2594 return start; 2595 } 2596 2597 /** 2598 * Walks a file tree. 2599 * 2600 * <p> This method works as if invoking it were equivalent to evaluating the 2601 * expression: 2602 * <blockquote><pre> 2603 * walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor) 2604 * </pre></blockquote> 2605 * In other words, it does not follow symbolic links, and visits all levels 2606 * of the file tree. 2607 * 2608 * @param start 2609 * the starting file 2610 * @param visitor 2611 * the file visitor to invoke for each file 2612 * 2613 * @return the starting file 2614 * 2615 * @throws SecurityException 2616 * If the security manager denies access to the starting file. 2617 * In the case of the default provider, the {@link 2618 * SecurityManager#checkRead(String) checkRead} method is invoked 2619 * to check read access to the directory. 2620 * @throws IOException 2621 * if an I/O error is thrown by a visitor method 2622 */ 2623 public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) 2624 throws IOException 2625 { 2626 return walkFileTree(start, 2627 EnumSet.noneOf(FileVisitOption.class), 2628 Integer.MAX_VALUE, 2629 visitor); 2630 } 2631 2632 2633 // -- Utility methods for simple usages -- 2634 2635 // buffer size used for reading and writing 2636 private static final int BUFFER_SIZE = 8192; 2637 2638 /** 2639 * Opens a file for reading, returning a {@code BufferedReader} that may be 2640 * used to read text from the file in an efficient manner. Bytes from the 2641 * file are decoded into characters using the specified charset. Reading 2642 * commences at the beginning of the file. 2643 * 2644 * <p> The {@code Reader} methods that read from the file throw {@code 2645 * IOException} if a malformed or unmappable byte sequence is read. 2646 * 2647 * @param path 2648 * the path to the file 2649 * @param cs 2650 * the charset to use for decoding 2651 * 2652 * @return a new buffered reader, with default buffer size, to read text 2653 * from the file 2654 * 2655 * @throws IOException 2656 * if an I/O error occurs opening the file 2657 * @throws SecurityException 2658 * In the case of the default provider, and a security manager is 2659 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2660 * method is invoked to check read access to the file. 2661 * 2662 * @see #readAllLines 2663 */ 2664 public static BufferedReader newBufferedReader(Path path, Charset cs) 2665 throws IOException 2666 { 2667 CharsetDecoder decoder = cs.newDecoder(); 2668 Reader reader = new InputStreamReader(newInputStream(path), decoder); 2669 return new BufferedReader(reader); 2670 } 2671 2672 /** 2673 * Opens or creates a file for writing, returning a {@code BufferedWriter} 2674 * that may be used to write text to the file in an efficient manner. 2675 * The {@code options} parameter specifies how the the file is created or 2676 * opened. If no options are present then this method works as if the {@link 2677 * StandardOpenOption#CREATE CREATE}, {@link 2678 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 2679 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 2680 * opens the file for writing, creating the file if it doesn't exist, or 2681 * initially truncating an existing {@link #isRegularFile regular-file} to 2682 * a size of {@code 0} if it exists. 2683 * 2684 * <p> The {@code Writer} methods to write text throw {@code IOException} 2685 * if the text cannot be encoded using the specified charset. 2686 * 2687 * @param path 2688 * the path to the file 2689 * @param cs 2690 * the charset to use for encoding 2691 * @param options 2692 * options specifying how the file is opened 2693 * 2694 * @return a new buffered writer, with default buffer size, to write text 2695 * to the file 2696 * 2697 * @throws IOException 2698 * if an I/O error occurs opening or creating the file 2699 * @throws UnsupportedOperationException 2700 * if an unsupported option is specified 2701 * @throws SecurityException 2702 * In the case of the default provider, and a security manager is 2703 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2704 * method is invoked to check write access to the file. 2705 * 2706 * @see #write(Path,Iterable,Charset,OpenOption[]) 2707 */ 2708 public static BufferedWriter newBufferedWriter(Path path, Charset cs, 2709 OpenOption... options) 2710 throws IOException 2711 { 2712 CharsetEncoder encoder = cs.newEncoder(); 2713 Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder); 2714 return new BufferedWriter(writer); 2715 } 2716 2717 /** 2718 * Reads all bytes from an input stream and writes them to an output stream. 2719 */ 2720 private static long copy(InputStream source, OutputStream sink) 2721 throws IOException 2722 { 2723 long nread = 0L; 2724 byte[] buf = new byte[BUFFER_SIZE]; 2725 int n; 2726 while ((n = source.read(buf)) > 0) { 2727 sink.write(buf, 0, n); 2728 nread += n; 2729 } 2730 return nread; 2731 } 2732 2733 /** 2734 * Copies all bytes from an input stream to a file. On return, the input 2735 * stream will be at end of stream. 2736 * 2737 * <p> By default, the copy fails if the target file already exists or is a 2738 * symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING 2739 * REPLACE_EXISTING} option is specified, and the target file already exists, 2740 * then it is replaced if it is not a non-empty directory. If the target 2741 * file exists and is a symbolic link, then the symbolic link is replaced. 2742 * In this release, the {@code REPLACE_EXISTING} option is the only option 2743 * required to be supported by this method. Additional options may be 2744 * supported in future releases. 2745 * 2746 * <p> If an I/O error occurs reading from the input stream or writing to 2747 * the file, then it may do so after the target file has been created and 2748 * after some bytes have been read or written. Consequently the input 2749 * stream may not be at end of stream and may be in an inconsistent state. 2750 * It is strongly recommended that the input stream be promptly closed if an 2751 * I/O error occurs. 2752 * 2753 * <p> This method may block indefinitely reading from the input stream (or 2754 * writing to the file). The behavior for the case that the input stream is 2755 * <i>asynchronously closed</i> or the thread interrupted during the copy is 2756 * highly input stream and file system provider specific and therefore not 2757 * specified. 2758 * 2759 * <p> <b>Usage example</b>: Suppose we want to capture a web page and save 2760 * it to a file: 2761 * <pre> 2762 * Path path = ... 2763 * URI u = URI.create("http://java.sun.com/"); 2764 * try (InputStream in = u.toURL().openStream()) { 2765 * Files.copy(in, path); 2766 * } 2767 * </pre> 2768 * 2769 * @param in 2770 * the input stream to read from 2771 * @param target 2772 * the path to the file 2773 * @param options 2774 * options specifying how the copy should be done 2775 * 2776 * @return the number of bytes read or written 2777 * 2778 * @throws IOException 2779 * if an I/O error occurs when reading or writing 2780 * @throws FileAlreadyExistsException 2781 * if the target file exists but cannot be replaced because the 2782 * {@code REPLACE_EXISTING} option is not specified <i>(optional 2783 * specific exception)</i> 2784 * @throws DirectoryNotEmptyException 2785 * the {@code REPLACE_EXISTING} option is specified but the file 2786 * cannot be replaced because it is a non-empty directory 2787 * <i>(optional specific exception)</i> * 2788 * @throws UnsupportedOperationException 2789 * if {@code options} contains a copy option that is not supported 2790 * @throws SecurityException 2791 * In the case of the default provider, and a security manager is 2792 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2793 * method is invoked to check write access to the file. Where the 2794 * {@code REPLACE_EXISTING} option is specified, the security 2795 * manager's {@link SecurityManager#checkDelete(String) checkDelete} 2796 * method is invoked to check that an existing file can be deleted. 2797 */ 2798 public static long copy(InputStream in, Path target, CopyOption... options) 2799 throws IOException 2800 { 2801 // ensure not null before opening file 2802 Objects.requireNonNull(in); 2803 2804 // check for REPLACE_EXISTING 2805 boolean replaceExisting = false; 2806 for (CopyOption opt: options) { 2807 if (opt == StandardCopyOption.REPLACE_EXISTING) { 2808 replaceExisting = true; 2809 } else { 2810 if (opt == null) { 2811 throw new NullPointerException("options contains 'null'"); 2812 } else { 2813 throw new UnsupportedOperationException(opt + " not supported"); 2814 } 2815 } 2816 } 2817 2818 // attempt to delete an existing file 2819 SecurityException se = null; 2820 if (replaceExisting) { 2821 try { 2822 deleteIfExists(target); 2823 } catch (SecurityException x) { 2824 se = x; 2825 } 2826 } 2827 2828 // attempt to create target file. If it fails with 2829 // FileAlreadyExistsException then it may be because the security 2830 // manager prevented us from deleting the file, in which case we just 2831 // throw the SecurityException. 2832 OutputStream ostream; 2833 try { 2834 ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW, 2835 StandardOpenOption.WRITE); 2836 } catch (FileAlreadyExistsException x) { 2837 if (se != null) 2838 throw se; 2839 // someone else won the race and created the file 2840 throw x; 2841 } 2842 2843 // do the copy 2844 try (OutputStream out = ostream) { 2845 return copy(in, out); 2846 } 2847 } 2848 2849 /** 2850 * Copies all bytes from a file to an output stream. 2851 * 2852 * <p> If an I/O error occurs reading from the file or writing to the output 2853 * stream, then it may do so after some bytes have been read or written. 2854 * Consequently the output stream may be in an inconsistent state. It is 2855 * strongly recommended that the output stream be promptly closed if an I/O 2856 * error occurs. 2857 * 2858 * <p> This method may block indefinitely writing to the output stream (or 2859 * reading from the file). The behavior for the case that the output stream 2860 * is <i>asynchronously closed</i> or the thread interrupted during the copy 2861 * is highly output stream and file system provider specific and therefore 2862 * not specified. 2863 * 2864 * <p> Note that if the given output stream is {@link java.io.Flushable} 2865 * then its {@link java.io.Flushable#flush flush} method may need to invoked 2866 * after this method completes so as to flush any buffered output. 2867 * 2868 * @param source 2869 * the path to the file 2870 * @param out 2871 * the output stream to write to 2872 * 2873 * @return the number of bytes read or written 2874 * 2875 * @throws IOException 2876 * if an I/O error occurs when reading or writing 2877 * @throws SecurityException 2878 * In the case of the default provider, and a security manager is 2879 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2880 * method is invoked to check read access to the file. 2881 */ 2882 public static long copy(Path source, OutputStream out) throws IOException { 2883 // ensure not null before opening file 2884 Objects.requireNonNull(out); 2885 2886 try (InputStream in = newInputStream(source)) { 2887 return copy(in, out); 2888 } 2889 } 2890 2891 /** 2892 * The maximum size of array to allocate. 2893 * Some VMs reserve some header words in an array. 2894 * Attempts to allocate larger arrays may result in 2895 * OutOfMemoryError: Requested array size exceeds VM limit 2896 */ 2897 private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; 2898 2899 /** 2900 * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint 2901 * about how many bytes the stream will have. 2902 * 2903 * @param source 2904 * the input stream to read from 2905 * @param initialSize 2906 * the initial size of the byte array to allocate 2907 * 2908 * @return a byte array containing the bytes read from the file 2909 * 2910 * @throws IOException 2911 * if an I/O error occurs reading from the stream 2912 * @throws OutOfMemoryError 2913 * if an array of the required size cannot be allocated 2914 */ 2915 private static byte[] read(InputStream source, int initialSize) 2916 throws IOException 2917 { 2918 int capacity = initialSize; 2919 byte[] buf = new byte[capacity]; 2920 int nread = 0; 2921 int n; 2922 for (;;) { 2923 // read to EOF which may read more or less than initialSize (eg: file 2924 // is truncated while we are reading) 2925 while ((n = source.read(buf, nread, capacity - nread)) > 0) 2926 nread += n; 2927 2928 // if last call to source.read() returned -1, we are done 2929 // otherwise, try to read one more byte; if that failed we're done too 2930 if (n < 0 || (n = source.read()) < 0) 2931 break; 2932 2933 // one more byte was read; need to allocate a larger buffer 2934 if (capacity <= MAX_BUFFER_SIZE - capacity) { 2935 capacity = Math.max(capacity << 1, BUFFER_SIZE); 2936 } else { 2937 if (capacity == MAX_BUFFER_SIZE) 2938 throw new OutOfMemoryError("Required array size too large"); 2939 capacity = MAX_BUFFER_SIZE; 2940 } 2941 buf = Arrays.copyOf(buf, capacity); 2942 buf[nread++] = (byte)n; 2943 } 2944 return (capacity == nread) ? buf : Arrays.copyOf(buf, nread); 2945 } 2946 2947 /** 2948 * Reads all the bytes from a file. The method ensures that the file is 2949 * closed when all bytes have been read or an I/O error, or other runtime 2950 * exception, is thrown. 2951 * 2952 * <p> Note that this method is intended for simple cases where it is 2953 * convenient to read all bytes into a byte array. It is not intended for 2954 * reading in large files. 2955 * 2956 * @param path 2957 * the path to the file 2958 * 2959 * @return a byte array containing the bytes read from the file 2960 * 2961 * @throws IOException 2962 * if an I/O error occurs reading from the stream 2963 * @throws OutOfMemoryError 2964 * if an array of the required size cannot be allocated, for 2965 * example the file is larger that {@code 2GB} 2966 * @throws SecurityException 2967 * In the case of the default provider, and a security manager is 2968 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2969 * method is invoked to check read access to the file. 2970 */ 2971 public static byte[] readAllBytes(Path path) throws IOException { 2972 try (FileChannel fc = FileChannel.open(path); 2973 InputStream is = Channels.newInputStream(fc)) { 2974 long size = fc.size(); 2975 if (size > (long)MAX_BUFFER_SIZE) 2976 throw new OutOfMemoryError("Required array size too large"); 2977 2978 return read(is, (int)size); 2979 } 2980 } 2981 2982 /** 2983 * Read all lines from a file. This method ensures that the file is 2984 * closed when all bytes have been read or an I/O error, or other runtime 2985 * exception, is thrown. Bytes from the file are decoded into characters 2986 * using the specified charset. 2987 * 2988 * <p> This method recognizes the following as line terminators: 2989 * <ul> 2990 * <li> <code>\u000D</code> followed by <code>\u000A</code>, 2991 * CARRIAGE RETURN followed by LINE FEED </li> 2992 * <li> <code>\u000A</code>, LINE FEED </li> 2993 * <li> <code>\u000D</code>, CARRIAGE RETURN </li> 2994 * </ul> 2995 * <p> Additional Unicode line terminators may be recognized in future 2996 * releases. 2997 * 2998 * <p> Note that this method is intended for simple cases where it is 2999 * convenient to read all lines in a single operation. It is not intended 3000 * for reading in large files. 3001 * 3002 * @param path 3003 * the path to the file 3004 * @param cs 3005 * the charset to use for decoding 3006 * 3007 * @return the lines from the file as a {@code List}; whether the {@code 3008 * List} is modifiable or not is implementation dependent and 3009 * therefore not specified 3010 * 3011 * @throws IOException 3012 * if an I/O error occurs reading from the file or a malformed or 3013 * unmappable byte sequence is read 3014 * @throws SecurityException 3015 * In the case of the default provider, and a security manager is 3016 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3017 * method is invoked to check read access to the file. 3018 * 3019 * @see #newBufferedReader 3020 */ 3021 public static List<String> readAllLines(Path path, Charset cs) 3022 throws IOException 3023 { 3024 try (BufferedReader reader = newBufferedReader(path, cs)) { 3025 List<String> result = new ArrayList<>(); 3026 for (;;) { 3027 String line = reader.readLine(); 3028 if (line == null) 3029 break; 3030 result.add(line); 3031 } 3032 return result; 3033 } 3034 } 3035 3036 /** 3037 * Writes bytes to a file. The {@code options} parameter specifies how the 3038 * the file is created or opened. If no options are present then this method 3039 * works as if the {@link StandardOpenOption#CREATE CREATE}, {@link 3040 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3041 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3042 * opens the file for writing, creating the file if it doesn't exist, or 3043 * initially truncating an existing {@link #isRegularFile regular-file} to 3044 * a size of {@code 0}. All bytes in the byte array are written to the file. 3045 * The method ensures that the file is closed when all bytes have been 3046 * written (or an I/O error or other runtime exception is thrown). If an I/O 3047 * error occurs then it may do so after the file has created or truncated, 3048 * or after some bytes have been written to the file. 3049 * 3050 * <p> <b>Usage example</b>: By default the method creates a new file or 3051 * overwrites an existing file. Suppose you instead want to append bytes 3052 * to an existing file: 3053 * <pre> 3054 * Path path = ... 3055 * byte[] bytes = ... 3056 * Files.write(path, bytes, StandardOpenOption.APPEND); 3057 * </pre> 3058 * 3059 * @param path 3060 * the path to the file 3061 * @param bytes 3062 * the byte array with the bytes to write 3063 * @param options 3064 * options specifying how the file is opened 3065 * 3066 * @return the path 3067 * 3068 * @throws IOException 3069 * if an I/O error occurs writing to or creating the file 3070 * @throws UnsupportedOperationException 3071 * if an unsupported option is specified 3072 * @throws SecurityException 3073 * In the case of the default provider, and a security manager is 3074 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3075 * method is invoked to check write access to the file. 3076 */ 3077 public static Path write(Path path, byte[] bytes, OpenOption... options) 3078 throws IOException 3079 { 3080 // ensure bytes is not null before opening file 3081 Objects.requireNonNull(bytes); 3082 3083 try (OutputStream out = Files.newOutputStream(path, options)) { 3084 int len = bytes.length; 3085 int rem = len; 3086 while (rem > 0) { 3087 int n = Math.min(rem, BUFFER_SIZE); 3088 out.write(bytes, (len-rem), n); 3089 rem -= n; 3090 } 3091 } 3092 return path; 3093 } 3094 3095 /** 3096 * Write lines of text to a file. Each line is a char sequence and is 3097 * written to the file in sequence with each line terminated by the 3098 * platform's line separator, as defined by the system property {@code 3099 * line.separator}. Characters are encoded into bytes using the specified 3100 * charset. 3101 * 3102 * <p> The {@code options} parameter specifies how the the file is created 3103 * or opened. If no options are present then this method works as if the 3104 * {@link StandardOpenOption#CREATE CREATE}, {@link 3105 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3106 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3107 * opens the file for writing, creating the file if it doesn't exist, or 3108 * initially truncating an existing {@link #isRegularFile regular-file} to 3109 * a size of {@code 0}. The method ensures that the file is closed when all 3110 * lines have been written (or an I/O error or other runtime exception is 3111 * thrown). If an I/O error occurs then it may do so after the file has 3112 * created or truncated, or after some bytes have been written to the file. 3113 * 3114 * @param path 3115 * the path to the file 3116 * @param lines 3117 * an object to iterate over the char sequences 3118 * @param cs 3119 * the charset to use for encoding 3120 * @param options 3121 * options specifying how the file is opened 3122 * 3123 * @return the path 3124 * 3125 * @throws IOException 3126 * if an I/O error occurs writing to or creating the file, or the 3127 * text cannot be encoded using the specified charset 3128 * @throws UnsupportedOperationException 3129 * if an unsupported option is specified 3130 * @throws SecurityException 3131 * In the case of the default provider, and a security manager is 3132 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3133 * method is invoked to check write access to the file. 3134 */ 3135 public static Path write(Path path, Iterable<? extends CharSequence> lines, 3136 Charset cs, OpenOption... options) 3137 throws IOException 3138 { 3139 // ensure lines is not null before opening file 3140 Objects.requireNonNull(lines); 3141 CharsetEncoder encoder = cs.newEncoder(); 3142 OutputStream out = newOutputStream(path, options); 3143 try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) { 3144 for (CharSequence line: lines) { 3145 writer.append(line); 3146 writer.newLine(); 3147 } 3148 } 3149 return path; 3150 } 3151 }