1 /* 2 * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.nio.file; 27 28 import java.io.BufferedReader; 29 import java.io.BufferedWriter; 30 import java.io.Closeable; 31 import java.io.File; 32 import java.io.IOException; 33 import java.io.InputStream; 34 import java.io.InputStreamReader; 35 import java.io.OutputStream; 36 import java.io.OutputStreamWriter; 37 import java.io.Reader; 38 import java.io.UncheckedIOException; 39 import java.io.Writer; 40 import java.nio.channels.Channels; 41 import java.nio.channels.FileChannel; 42 import java.nio.channels.SeekableByteChannel; 43 import java.nio.charset.Charset; 44 import java.nio.charset.CharsetDecoder; 45 import java.nio.charset.CharsetEncoder; 46 import java.nio.charset.StandardCharsets; 47 import java.nio.file.attribute.BasicFileAttributeView; 48 import java.nio.file.attribute.BasicFileAttributes; 49 import java.nio.file.attribute.DosFileAttributes; // javadoc 50 import java.nio.file.attribute.FileAttribute; 51 import java.nio.file.attribute.FileAttributeView; 52 import java.nio.file.attribute.FileOwnerAttributeView; 53 import java.nio.file.attribute.FileStoreAttributeView; 54 import java.nio.file.attribute.FileTime; 55 import java.nio.file.attribute.PosixFileAttributeView; 56 import java.nio.file.attribute.PosixFileAttributes; 57 import java.nio.file.attribute.PosixFilePermission; 58 import java.nio.file.attribute.UserPrincipal; 59 import java.nio.file.spi.FileSystemProvider; 60 import java.nio.file.spi.FileTypeDetector; 61 import java.security.AccessController; 62 import java.security.PrivilegedAction; 63 import java.util.ArrayList; 64 import java.util.Arrays; 65 import java.util.Collections; 66 import java.util.EnumSet; 67 import java.util.HashSet; 68 import java.util.Iterator; 69 import java.util.List; 70 import java.util.Map; 71 import java.util.Objects; 72 import java.util.ServiceLoader; 73 import java.util.Set; 74 import java.util.Spliterator; 75 import java.util.Spliterators; 76 import java.util.function.BiPredicate; 77 import java.util.stream.Stream; 78 import java.util.stream.StreamSupport; 79 80 import jdk.internal.util.ArraysSupport; 81 import sun.nio.ch.FileChannelImpl; 82 import sun.nio.fs.AbstractFileSystemProvider; 83 84 /** 85 * This class consists exclusively of static methods that operate on files, 86 * directories, or other types of files. 87 * 88 * <p> In most cases, the methods defined here will delegate to the associated 89 * file system provider to perform the file operations. 90 * 91 * @since 1.7 92 */ 93 94 public final class Files { 95 // buffer size used for reading and writing 96 private static final int BUFFER_SIZE = 8192; 97 98 private Files() { } 99 100 /** 101 * Returns the {@code FileSystemProvider} to delegate to. 102 */ 103 private static FileSystemProvider provider(Path path) { 104 return path.getFileSystem().provider(); 105 } 106 107 /** 108 * Convert a Closeable to a Runnable by converting checked IOException 109 * to UncheckedIOException 110 */ 111 private static Runnable asUncheckedRunnable(Closeable c) { 112 return () -> { 113 try { 114 c.close(); 115 } catch (IOException e) { 116 throw new UncheckedIOException(e); 117 } 118 }; 119 } 120 121 // -- File contents -- 122 123 /** 124 * Opens a file, returning an input stream to read from the file. The stream 125 * will not be buffered, and is not required to support the {@link 126 * InputStream#mark mark} or {@link InputStream#reset reset} methods. The 127 * stream will be safe for access by multiple concurrent threads. Reading 128 * commences at the beginning of the file. Whether the returned stream is 129 * <i>asynchronously closeable</i> and/or <i>interruptible</i> is highly 130 * file system provider specific and therefore not specified. 131 * 132 * <p> The {@code options} parameter determines how the file is opened. 133 * If no options are present then it is equivalent to opening the file with 134 * the {@link StandardOpenOption#READ READ} option. In addition to the {@code 135 * READ} option, an implementation may also support additional implementation 136 * specific options. 137 * 138 * @param path 139 * the path to the file to open 140 * @param options 141 * options specifying how the file is opened 142 * 143 * @return a new input stream 144 * 145 * @throws IllegalArgumentException 146 * if an invalid combination of options is specified 147 * @throws UnsupportedOperationException 148 * if an unsupported option is specified 149 * @throws IOException 150 * if an I/O error occurs 151 * @throws SecurityException 152 * In the case of the default provider, and a security manager is 153 * installed, the {@link SecurityManager#checkRead(String) checkRead} 154 * method is invoked to check read access to the file. 155 */ 156 public static InputStream newInputStream(Path path, OpenOption... options) 157 throws IOException 158 { 159 return provider(path).newInputStream(path, options); 160 } 161 162 /** 163 * Opens or creates a file, returning an output stream that may be used to 164 * write bytes to the file. The resulting stream will not be buffered. The 165 * stream will be safe for access by multiple concurrent threads. Whether 166 * the returned stream is <i>asynchronously closeable</i> and/or 167 * <i>interruptible</i> is highly file system provider specific and 168 * therefore not specified. 169 * 170 * <p> This method opens or creates a file in exactly the manner specified 171 * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel} 172 * method with the exception that the {@link StandardOpenOption#READ READ} 173 * option may not be present in the array of options. If no options are 174 * present then this method works as if the {@link StandardOpenOption#CREATE 175 * CREATE}, {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, 176 * and {@link StandardOpenOption#WRITE WRITE} options are present. In other 177 * words, it opens the file for writing, creating the file if it doesn't 178 * exist, or initially truncating an existing {@link #isRegularFile 179 * regular-file} to a size of {@code 0} if it exists. 180 * 181 * <p> <b>Usage Examples:</b> 182 * <pre> 183 * Path path = ... 184 * 185 * // truncate and overwrite an existing file, or create the file if 186 * // it doesn't initially exist 187 * OutputStream out = Files.newOutputStream(path); 188 * 189 * // append to an existing file, fail if the file does not exist 190 * out = Files.newOutputStream(path, APPEND); 191 * 192 * // append to an existing file, create file if it doesn't initially exist 193 * out = Files.newOutputStream(path, CREATE, APPEND); 194 * 195 * // always create new file, failing if it already exists 196 * out = Files.newOutputStream(path, CREATE_NEW); 197 * </pre> 198 * 199 * @param path 200 * the path to the file to open or create 201 * @param options 202 * options specifying how the file is opened 203 * 204 * @return a new output stream 205 * 206 * @throws IllegalArgumentException 207 * if {@code options} contains an invalid combination of options 208 * @throws UnsupportedOperationException 209 * if an unsupported option is specified 210 * @throws IOException 211 * if an I/O error occurs 212 * @throws SecurityException 213 * In the case of the default provider, and a security manager is 214 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 215 * method is invoked to check write access to the file. The {@link 216 * SecurityManager#checkDelete(String) checkDelete} method is 217 * invoked to check delete access if the file is opened with the 218 * {@code DELETE_ON_CLOSE} option. 219 */ 220 public static OutputStream newOutputStream(Path path, OpenOption... options) 221 throws IOException 222 { 223 return provider(path).newOutputStream(path, options); 224 } 225 226 /** 227 * Opens or creates a file, returning a seekable byte channel to access the 228 * file. 229 * 230 * <p> The {@code options} parameter determines how the file is opened. 231 * The {@link StandardOpenOption#READ READ} and {@link 232 * StandardOpenOption#WRITE WRITE} options determine if the file should be 233 * opened for reading and/or writing. If neither option (or the {@link 234 * StandardOpenOption#APPEND APPEND} option) is present then the file is 235 * opened for reading. By default reading or writing commence at the 236 * beginning of the file. 237 * 238 * <p> In the addition to {@code READ} and {@code WRITE}, the following 239 * options may be present: 240 * 241 * <table class="striped"> 242 * <caption style="display:none">Options</caption> 243 * <thead> 244 * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> 245 * </thead> 246 * <tbody> 247 * <tr> 248 * <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th> 249 * <td> If this option is present then the file is opened for writing and 250 * each invocation of the channel's {@code write} method first advances 251 * the position to the end of the file and then writes the requested 252 * data. Whether the advancement of the position and the writing of the 253 * data are done in a single atomic operation is system-dependent and 254 * therefore unspecified. This option may not be used in conjunction 255 * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> 256 * </tr> 257 * <tr> 258 * <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th> 259 * <td> If this option is present then the existing file is truncated to 260 * a size of 0 bytes. This option is ignored when the file is opened only 261 * for reading. </td> 262 * </tr> 263 * <tr> 264 * <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th> 265 * <td> If this option is present then a new file is created, failing if 266 * the file already exists or is a symbolic link. When creating a file the 267 * check for the existence of the file and the creation of the file if it 268 * does not exist is atomic with respect to other file system operations. 269 * This option is ignored when the file is opened only for reading. </td> 270 * </tr> 271 * <tr> 272 * <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th> 273 * <td> If this option is present then an existing file is opened if it 274 * exists, otherwise a new file is created. This option is ignored if the 275 * {@code CREATE_NEW} option is also present or the file is opened only 276 * for reading. </td> 277 * </tr> 278 * <tr> 279 * <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th> 280 * <td> When this option is present then the implementation makes a 281 * <em>best effort</em> attempt to delete the file when closed by the 282 * {@link SeekableByteChannel#close close} method. If the {@code close} 283 * method is not invoked then a <em>best effort</em> attempt is made to 284 * delete the file when the Java virtual machine terminates. </td> 285 * </tr> 286 * <tr> 287 * <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th> 288 * <td> When creating a new file this option is a <em>hint</em> that the 289 * new file will be sparse. This option is ignored when not creating 290 * a new file. </td> 291 * </tr> 292 * <tr> 293 * <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th> 294 * <td> Requires that every update to the file's content or metadata be 295 * written synchronously to the underlying storage device. (see <a 296 * href="package-summary.html#integrity"> Synchronized I/O file 297 * integrity</a>). </td> 298 * </tr> 299 * <tr> 300 * <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th> 301 * <td> Requires that every update to the file's content be written 302 * synchronously to the underlying storage device. (see <a 303 * href="package-summary.html#integrity"> Synchronized I/O file 304 * integrity</a>). </td> 305 * </tr> 306 * </tbody> 307 * </table> 308 * 309 * <p> An implementation may also support additional implementation specific 310 * options. 311 * 312 * <p> The {@code attrs} parameter is optional {@link FileAttribute 313 * file-attributes} to set atomically when a new file is created. 314 * 315 * <p> In the case of the default provider, the returned seekable byte channel 316 * is a {@link java.nio.channels.FileChannel}. 317 * 318 * <p> <b>Usage Examples:</b> 319 * <pre>{@code 320 * Path path = ... 321 * 322 * // open file for reading 323 * ReadableByteChannel rbc = Files.newByteChannel(path, EnumSet.of(READ))); 324 * 325 * // open file for writing to the end of an existing file, creating 326 * // the file if it doesn't already exist 327 * WritableByteChannel wbc = Files.newByteChannel(path, EnumSet.of(CREATE,APPEND)); 328 * 329 * // create file with initial permissions, opening it for both reading and writing 330 * FileAttribute<Set<PosixFilePermission>> perms = ... 331 * SeekableByteChannel sbc = 332 * Files.newByteChannel(path, EnumSet.of(CREATE_NEW,READ,WRITE), perms); 333 * }</pre> 334 * 335 * @param path 336 * the path to the file to open or create 337 * @param options 338 * options specifying how the file is opened 339 * @param attrs 340 * an optional list of file attributes to set atomically when 341 * creating the file 342 * 343 * @return a new seekable byte channel 344 * 345 * @throws IllegalArgumentException 346 * if the set contains an invalid combination of options 347 * @throws UnsupportedOperationException 348 * if an unsupported open option is specified or the array contains 349 * attributes that cannot be set atomically when creating the file 350 * @throws FileAlreadyExistsException 351 * if a file of that name already exists and the {@link 352 * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified 353 * <i>(optional specific exception)</i> 354 * @throws IOException 355 * if an I/O error occurs 356 * @throws SecurityException 357 * In the case of the default provider, and a security manager is 358 * installed, the {@link SecurityManager#checkRead(String) checkRead} 359 * method is invoked to check read access to the path if the file is 360 * opened for reading. The {@link SecurityManager#checkWrite(String) 361 * checkWrite} method is invoked to check write access to the path 362 * if the file is opened for writing. The {@link 363 * SecurityManager#checkDelete(String) checkDelete} method is 364 * invoked to check delete access if the file is opened with the 365 * {@code DELETE_ON_CLOSE} option. 366 * 367 * @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[]) 368 */ 369 public static SeekableByteChannel newByteChannel(Path path, 370 Set<? extends OpenOption> options, 371 FileAttribute<?>... attrs) 372 throws IOException 373 { 374 return provider(path).newByteChannel(path, options, attrs); 375 } 376 377 /** 378 * Opens or creates a file, returning a seekable byte channel to access the 379 * file. 380 * 381 * <p> This method opens or creates a file in exactly the manner specified 382 * by the {@link #newByteChannel(Path,Set,FileAttribute[]) newByteChannel} 383 * method. 384 * 385 * @param path 386 * the path to the file to open or create 387 * @param options 388 * options specifying how the file is opened 389 * 390 * @return a new seekable byte channel 391 * 392 * @throws IllegalArgumentException 393 * if the set contains an invalid combination of options 394 * @throws UnsupportedOperationException 395 * if an unsupported open option is specified 396 * @throws FileAlreadyExistsException 397 * if a file of that name already exists and the {@link 398 * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified 399 * <i>(optional specific exception)</i> 400 * @throws IOException 401 * if an I/O error occurs 402 * @throws SecurityException 403 * In the case of the default provider, and a security manager is 404 * installed, the {@link SecurityManager#checkRead(String) checkRead} 405 * method is invoked to check read access to the path if the file is 406 * opened for reading. The {@link SecurityManager#checkWrite(String) 407 * checkWrite} method is invoked to check write access to the path 408 * if the file is opened for writing. The {@link 409 * SecurityManager#checkDelete(String) checkDelete} method is 410 * invoked to check delete access if the file is opened with the 411 * {@code DELETE_ON_CLOSE} option. 412 * 413 * @see java.nio.channels.FileChannel#open(Path,OpenOption[]) 414 */ 415 public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) 416 throws IOException 417 { 418 Set<OpenOption> set; 419 if (options.length == 0) { 420 set = Collections.emptySet(); 421 } else { 422 set = new HashSet<>(); 423 Collections.addAll(set, options); 424 } 425 return newByteChannel(path, set); 426 } 427 428 // -- Directories -- 429 430 private static class AcceptAllFilter 431 implements DirectoryStream.Filter<Path> 432 { 433 private AcceptAllFilter() { } 434 435 @Override 436 public boolean accept(Path entry) { return true; } 437 438 static final AcceptAllFilter FILTER = new AcceptAllFilter(); 439 } 440 441 /** 442 * Opens a directory, returning a {@link DirectoryStream} to iterate over 443 * all entries in the directory. The elements returned by the directory 444 * stream's {@link DirectoryStream#iterator iterator} are of type {@code 445 * Path}, each one representing an entry in the directory. The {@code Path} 446 * objects are obtained as if by {@link Path#resolve(Path) resolving} the 447 * name of the directory entry against {@code dir}. 448 * 449 * <p> When not using the try-with-resources construct, then directory 450 * stream's {@code close} method should be invoked after iteration is 451 * completed so as to free any resources held for the open directory. 452 * 453 * <p> When an implementation supports operations on entries in the 454 * directory that execute in a race-free manner then the returned directory 455 * stream is a {@link SecureDirectoryStream}. 456 * 457 * @param dir 458 * the path to the directory 459 * 460 * @return a new and open {@code DirectoryStream} object 461 * 462 * @throws NotDirectoryException 463 * if the file could not otherwise be opened because it is not 464 * a directory <i>(optional specific exception)</i> 465 * @throws IOException 466 * if an I/O error occurs 467 * @throws SecurityException 468 * In the case of the default provider, and a security manager is 469 * installed, the {@link SecurityManager#checkRead(String) checkRead} 470 * method is invoked to check read access to the directory. 471 */ 472 public static DirectoryStream<Path> newDirectoryStream(Path dir) 473 throws IOException 474 { 475 return provider(dir).newDirectoryStream(dir, AcceptAllFilter.FILTER); 476 } 477 478 /** 479 * Opens a directory, returning a {@link DirectoryStream} to iterate over 480 * the entries in the directory. The elements returned by the directory 481 * stream's {@link DirectoryStream#iterator iterator} are of type {@code 482 * Path}, each one representing an entry in the directory. The {@code Path} 483 * objects are obtained as if by {@link Path#resolve(Path) resolving} the 484 * name of the directory entry against {@code dir}. The entries returned by 485 * the iterator are filtered by matching the {@code String} representation 486 * of their file names against the given <em>globbing</em> pattern. 487 * 488 * <p> For example, suppose we want to iterate over the files ending with 489 * ".java" in a directory: 490 * <pre> 491 * Path dir = ... 492 * try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")) { 493 * : 494 * } 495 * </pre> 496 * 497 * <p> The globbing pattern is specified by the {@link 498 * FileSystem#getPathMatcher getPathMatcher} method. 499 * 500 * <p> When not using the try-with-resources construct, then directory 501 * stream's {@code close} method should be invoked after iteration is 502 * completed so as to free any resources held for the open directory. 503 * 504 * <p> When an implementation supports operations on entries in the 505 * directory that execute in a race-free manner then the returned directory 506 * stream is a {@link SecureDirectoryStream}. 507 * 508 * @param dir 509 * the path to the directory 510 * @param glob 511 * the glob pattern 512 * 513 * @return a new and open {@code DirectoryStream} object 514 * 515 * @throws java.util.regex.PatternSyntaxException 516 * if the pattern is invalid 517 * @throws NotDirectoryException 518 * if the file could not otherwise be opened because it is not 519 * a directory <i>(optional specific exception)</i> 520 * @throws IOException 521 * if an I/O error occurs 522 * @throws SecurityException 523 * In the case of the default provider, and a security manager is 524 * installed, the {@link SecurityManager#checkRead(String) checkRead} 525 * method is invoked to check read access to the directory. 526 */ 527 public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) 528 throws IOException 529 { 530 // avoid creating a matcher if all entries are required. 531 if (glob.equals("*")) 532 return newDirectoryStream(dir); 533 534 // create a matcher and return a filter that uses it. 535 FileSystem fs = dir.getFileSystem(); 536 final PathMatcher matcher = fs.getPathMatcher("glob:" + glob); 537 DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<>() { 538 @Override 539 public boolean accept(Path entry) { 540 return matcher.matches(entry.getFileName()); 541 } 542 }; 543 return fs.provider().newDirectoryStream(dir, filter); 544 } 545 546 /** 547 * Opens a directory, returning a {@link DirectoryStream} to iterate over 548 * the entries in the directory. The elements returned by the directory 549 * stream's {@link DirectoryStream#iterator iterator} are of type {@code 550 * Path}, each one representing an entry in the directory. The {@code Path} 551 * objects are obtained as if by {@link Path#resolve(Path) resolving} the 552 * name of the directory entry against {@code dir}. The entries returned by 553 * the iterator are filtered by the given {@link DirectoryStream.Filter 554 * filter}. 555 * 556 * <p> When not using the try-with-resources construct, then directory 557 * stream's {@code close} method should be invoked after iteration is 558 * completed so as to free any resources held for the open directory. 559 * 560 * <p> Where the filter terminates due to an uncaught error or runtime 561 * exception then it is propagated to the {@link Iterator#hasNext() 562 * hasNext} or {@link Iterator#next() next} method. Where an {@code 563 * IOException} is thrown, it results in the {@code hasNext} or {@code 564 * next} method throwing a {@link DirectoryIteratorException} with the 565 * {@code IOException} as the cause. 566 * 567 * <p> When an implementation supports operations on entries in the 568 * directory that execute in a race-free manner then the returned directory 569 * stream is a {@link SecureDirectoryStream}. 570 * 571 * <p> <b>Usage Example:</b> 572 * Suppose we want to iterate over the files in a directory that are 573 * larger than 8K. 574 * <pre> 575 * DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { 576 * public boolean accept(Path file) throws IOException { 577 * return (Files.size(file) > 8192L); 578 * } 579 * }; 580 * Path dir = ... 581 * try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) { 582 * : 583 * } 584 * </pre> 585 * 586 * @param dir 587 * the path to the directory 588 * @param filter 589 * the directory stream filter 590 * 591 * @return a new and open {@code DirectoryStream} object 592 * 593 * @throws NotDirectoryException 594 * if the file could not otherwise be opened because it is not 595 * a directory <i>(optional specific exception)</i> 596 * @throws IOException 597 * if an I/O error occurs 598 * @throws SecurityException 599 * In the case of the default provider, and a security manager is 600 * installed, the {@link SecurityManager#checkRead(String) checkRead} 601 * method is invoked to check read access to the directory. 602 */ 603 public static DirectoryStream<Path> newDirectoryStream(Path dir, 604 DirectoryStream.Filter<? super Path> filter) 605 throws IOException 606 { 607 return provider(dir).newDirectoryStream(dir, filter); 608 } 609 610 // -- Creation and deletion -- 611 612 private static final Set<OpenOption> DEFAULT_CREATE_OPTIONS = 613 Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); 614 615 /** 616 * Creates a new and empty file, failing if the file already exists. The 617 * check for the existence of the file and the creation of the new file if 618 * it does not exist are a single operation that is atomic with respect to 619 * all other filesystem activities that might affect the directory. 620 * 621 * <p> The {@code attrs} parameter is optional {@link FileAttribute 622 * file-attributes} to set atomically when creating the file. Each attribute 623 * is identified by its {@link FileAttribute#name name}. If more than one 624 * attribute of the same name is included in the array then all but the last 625 * occurrence is ignored. 626 * 627 * @param path 628 * the path to the file to create 629 * @param attrs 630 * an optional list of file attributes to set atomically when 631 * creating the file 632 * 633 * @return the file 634 * 635 * @throws UnsupportedOperationException 636 * if the array contains an attribute that cannot be set atomically 637 * when creating the file 638 * @throws FileAlreadyExistsException 639 * if a file of that name already exists 640 * <i>(optional specific exception)</i> 641 * @throws IOException 642 * if an I/O error occurs or the parent directory does not exist 643 * @throws SecurityException 644 * In the case of the default provider, and a security manager is 645 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 646 * method is invoked to check write access to the new file. 647 */ 648 public static Path createFile(Path path, FileAttribute<?>... attrs) 649 throws IOException 650 { 651 newByteChannel(path, DEFAULT_CREATE_OPTIONS, attrs).close(); 652 return path; 653 } 654 655 /** 656 * Creates a new directory. The check for the existence of the file and the 657 * creation of the directory if it does not exist are a single operation 658 * that is atomic with respect to all other filesystem activities that might 659 * affect the directory. The {@link #createDirectories createDirectories} 660 * method should be used where it is required to create all nonexistent 661 * parent directories first. 662 * 663 * <p> The {@code attrs} parameter is optional {@link FileAttribute 664 * file-attributes} to set atomically when creating the directory. Each 665 * attribute is identified by its {@link FileAttribute#name name}. If more 666 * than one attribute of the same name is included in the array then all but 667 * the last occurrence is ignored. 668 * 669 * @param dir 670 * the directory to create 671 * @param attrs 672 * an optional list of file attributes to set atomically when 673 * creating the directory 674 * 675 * @return the directory 676 * 677 * @throws UnsupportedOperationException 678 * if the array contains an attribute that cannot be set atomically 679 * when creating the directory 680 * @throws FileAlreadyExistsException 681 * if a directory could not otherwise be created because a file of 682 * that name already exists <i>(optional specific exception)</i> 683 * @throws IOException 684 * if an I/O error occurs or the parent directory does not exist 685 * @throws SecurityException 686 * In the case of the default provider, and a security manager is 687 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 688 * method is invoked to check write access to the new directory. 689 */ 690 public static Path createDirectory(Path dir, FileAttribute<?>... attrs) 691 throws IOException 692 { 693 provider(dir).createDirectory(dir, attrs); 694 return dir; 695 } 696 697 /** 698 * Creates a directory by creating all nonexistent parent directories first. 699 * Unlike the {@link #createDirectory createDirectory} method, an exception 700 * is not thrown if the directory could not be created because it already 701 * exists. 702 * 703 * <p> The {@code attrs} parameter is optional {@link FileAttribute 704 * file-attributes} to set atomically when creating the nonexistent 705 * directories. Each file attribute is identified by its {@link 706 * FileAttribute#name name}. If more than one attribute of the same name is 707 * included in the array then all but the last occurrence is ignored. 708 * 709 * <p> If this method fails, then it may do so after creating some, but not 710 * all, of the parent directories. 711 * 712 * @param dir 713 * the directory to create 714 * 715 * @param attrs 716 * an optional list of file attributes to set atomically when 717 * creating the directory 718 * 719 * @return the directory 720 * 721 * @throws UnsupportedOperationException 722 * if the array contains an attribute that cannot be set atomically 723 * when creating the directory 724 * @throws FileAlreadyExistsException 725 * if {@code dir} exists but is not a directory <i>(optional specific 726 * exception)</i> 727 * @throws IOException 728 * if an I/O error occurs 729 * @throws SecurityException 730 * in the case of the default provider, and a security manager is 731 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 732 * method is invoked prior to attempting to create a directory and 733 * its {@link SecurityManager#checkRead(String) checkRead} is 734 * invoked for each parent directory that is checked. If {@code 735 * dir} is not an absolute path then its {@link Path#toAbsolutePath 736 * toAbsolutePath} may need to be invoked to get its absolute path. 737 * This may invoke the security manager's {@link 738 * SecurityManager#checkPropertyAccess(String) checkPropertyAccess} 739 * method to check access to the system property {@code user.dir} 740 */ 741 public static Path createDirectories(Path dir, FileAttribute<?>... attrs) 742 throws IOException 743 { 744 // attempt to create the directory 745 try { 746 createAndCheckIsDirectory(dir, attrs); 747 return dir; 748 } catch (FileAlreadyExistsException x) { 749 // file exists and is not a directory 750 throw x; 751 } catch (IOException x) { 752 // parent may not exist or other reason 753 } 754 SecurityException se = null; 755 try { 756 dir = dir.toAbsolutePath(); 757 } catch (SecurityException x) { 758 // don't have permission to get absolute path 759 se = x; 760 } 761 // find a descendant that exists 762 Path parent = dir.getParent(); 763 while (parent != null) { 764 try { 765 provider(parent).checkAccess(parent); 766 break; 767 } catch (NoSuchFileException x) { 768 // does not exist 769 } 770 parent = parent.getParent(); 771 } 772 if (parent == null) { 773 // unable to find existing parent 774 if (se == null) { 775 throw new FileSystemException(dir.toString(), null, 776 "Unable to determine if root directory exists"); 777 } else { 778 throw se; 779 } 780 } 781 782 // create directories 783 Path child = parent; 784 for (Path name: parent.relativize(dir)) { 785 child = child.resolve(name); 786 createAndCheckIsDirectory(child, attrs); 787 } 788 return dir; 789 } 790 791 /** 792 * Used by createDirectories to attempt to create a directory. A no-op 793 * if the directory already exists. 794 */ 795 private static void createAndCheckIsDirectory(Path dir, 796 FileAttribute<?>... attrs) 797 throws IOException 798 { 799 try { 800 createDirectory(dir, attrs); 801 } catch (FileAlreadyExistsException x) { 802 if (!isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) 803 throw x; 804 } 805 } 806 807 /** 808 * Creates a new empty file in the specified directory, using the given 809 * prefix and suffix strings to generate its name. The resulting 810 * {@code Path} is associated with the same {@code FileSystem} as the given 811 * directory. 812 * 813 * <p> The details as to how the name of the file is constructed is 814 * implementation dependent and therefore not specified. Where possible 815 * the {@code prefix} and {@code suffix} are used to construct candidate 816 * names in the same manner as the {@link 817 * java.io.File#createTempFile(String,String,File)} method. 818 * 819 * <p> As with the {@code File.createTempFile} methods, this method is only 820 * part of a temporary-file facility. Where used as a <em>work files</em>, 821 * the resulting file may be opened using the {@link 822 * StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} option so that the 823 * file is deleted when the appropriate {@code close} method is invoked. 824 * Alternatively, a {@link Runtime#addShutdownHook shutdown-hook}, or the 825 * {@link java.io.File#deleteOnExit} mechanism may be used to delete the 826 * file automatically. 827 * 828 * <p> The {@code attrs} parameter is optional {@link FileAttribute 829 * file-attributes} to set atomically when creating the file. Each attribute 830 * is identified by its {@link FileAttribute#name name}. If more than one 831 * attribute of the same name is included in the array then all but the last 832 * occurrence is ignored. When no file attributes are specified, then the 833 * resulting file may have more restrictive access permissions to files 834 * created by the {@link java.io.File#createTempFile(String,String,File)} 835 * method. 836 * 837 * @param dir 838 * the path to directory in which to create the file 839 * @param prefix 840 * the prefix string to be used in generating the file's name; 841 * may be {@code null} 842 * @param suffix 843 * the suffix string to be used in generating the file's name; 844 * may be {@code null}, in which case "{@code .tmp}" is used 845 * @param attrs 846 * an optional list of file attributes to set atomically when 847 * creating the file 848 * 849 * @return the path to the newly created file that did not exist before 850 * this method was invoked 851 * 852 * @throws IllegalArgumentException 853 * if the prefix or suffix parameters cannot be used to generate 854 * a candidate file name 855 * @throws UnsupportedOperationException 856 * if the array contains an attribute that cannot be set atomically 857 * when creating the directory 858 * @throws IOException 859 * if an I/O error occurs or {@code dir} does not exist 860 * @throws SecurityException 861 * In the case of the default provider, and a security manager is 862 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 863 * method is invoked to check write access to the file. 864 */ 865 public static Path createTempFile(Path dir, 866 String prefix, 867 String suffix, 868 FileAttribute<?>... attrs) 869 throws IOException 870 { 871 return TempFileHelper.createTempFile(Objects.requireNonNull(dir), 872 prefix, suffix, attrs); 873 } 874 875 /** 876 * Creates an empty file in the default temporary-file directory, using 877 * the given prefix and suffix to generate its name. The resulting {@code 878 * Path} is associated with the default {@code FileSystem}. 879 * 880 * <p> This method works in exactly the manner specified by the 881 * {@link #createTempFile(Path,String,String,FileAttribute[])} method for 882 * the case that the {@code dir} parameter is the temporary-file directory. 883 * 884 * @param prefix 885 * the prefix string to be used in generating the file's name; 886 * may be {@code null} 887 * @param suffix 888 * the suffix string to be used in generating the file's name; 889 * may be {@code null}, in which case "{@code .tmp}" is used 890 * @param attrs 891 * an optional list of file attributes to set atomically when 892 * creating the file 893 * 894 * @return the path to the newly created file that did not exist before 895 * this method was invoked 896 * 897 * @throws IllegalArgumentException 898 * if the prefix or suffix parameters cannot be used to generate 899 * a candidate file name 900 * @throws UnsupportedOperationException 901 * if the array contains an attribute that cannot be set atomically 902 * when creating the directory 903 * @throws IOException 904 * if an I/O error occurs or the temporary-file directory does not 905 * exist 906 * @throws SecurityException 907 * In the case of the default provider, and a security manager is 908 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 909 * method is invoked to check write access to the file. 910 */ 911 public static Path createTempFile(String prefix, 912 String suffix, 913 FileAttribute<?>... attrs) 914 throws IOException 915 { 916 return TempFileHelper.createTempFile(null, prefix, suffix, attrs); 917 } 918 919 /** 920 * Creates a new directory in the specified directory, using the given 921 * prefix to generate its name. The resulting {@code Path} is associated 922 * with the same {@code FileSystem} as the given directory. 923 * 924 * <p> The details as to how the name of the directory is constructed is 925 * implementation dependent and therefore not specified. Where possible 926 * the {@code prefix} is used to construct candidate names. 927 * 928 * <p> As with the {@code createTempFile} methods, this method is only 929 * part of a temporary-file facility. A {@link Runtime#addShutdownHook 930 * shutdown-hook}, or the {@link java.io.File#deleteOnExit} mechanism may be 931 * used to delete the directory automatically. 932 * 933 * <p> The {@code attrs} parameter is optional {@link FileAttribute 934 * file-attributes} to set atomically when creating the directory. Each 935 * attribute is identified by its {@link FileAttribute#name name}. If more 936 * than one attribute of the same name is included in the array then all but 937 * the last occurrence is ignored. 938 * 939 * @param dir 940 * the path to directory in which to create the directory 941 * @param prefix 942 * the prefix string to be used in generating the directory's name; 943 * may be {@code null} 944 * @param attrs 945 * an optional list of file attributes to set atomically when 946 * creating the directory 947 * 948 * @return the path to the newly created directory that did not exist before 949 * this method was invoked 950 * 951 * @throws IllegalArgumentException 952 * if the prefix cannot be used to generate a candidate directory name 953 * @throws UnsupportedOperationException 954 * if the array contains an attribute that cannot be set atomically 955 * when creating the directory 956 * @throws IOException 957 * if an I/O error occurs or {@code dir} does not exist 958 * @throws SecurityException 959 * In the case of the default provider, and a security manager is 960 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 961 * method is invoked to check write access when creating the 962 * directory. 963 */ 964 public static Path createTempDirectory(Path dir, 965 String prefix, 966 FileAttribute<?>... attrs) 967 throws IOException 968 { 969 return TempFileHelper.createTempDirectory(Objects.requireNonNull(dir), 970 prefix, attrs); 971 } 972 973 /** 974 * Creates a new directory in the default temporary-file directory, using 975 * the given prefix to generate its name. The resulting {@code Path} is 976 * associated with the default {@code FileSystem}. 977 * 978 * <p> This method works in exactly the manner specified by {@link 979 * #createTempDirectory(Path,String,FileAttribute[])} method for the case 980 * that the {@code dir} parameter is the temporary-file directory. 981 * 982 * @param prefix 983 * the prefix string to be used in generating the directory's name; 984 * may be {@code null} 985 * @param attrs 986 * an optional list of file attributes to set atomically when 987 * creating the directory 988 * 989 * @return the path to the newly created directory that did not exist before 990 * this method was invoked 991 * 992 * @throws IllegalArgumentException 993 * if the prefix cannot be used to generate a candidate directory name 994 * @throws UnsupportedOperationException 995 * if the array contains an attribute that cannot be set atomically 996 * when creating the directory 997 * @throws IOException 998 * if an I/O error occurs or the temporary-file directory does not 999 * exist 1000 * @throws SecurityException 1001 * In the case of the default provider, and a security manager is 1002 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 1003 * method is invoked to check write access when creating the 1004 * directory. 1005 */ 1006 public static Path createTempDirectory(String prefix, 1007 FileAttribute<?>... attrs) 1008 throws IOException 1009 { 1010 return TempFileHelper.createTempDirectory(null, prefix, attrs); 1011 } 1012 1013 /** 1014 * Creates a symbolic link to a target <i>(optional operation)</i>. 1015 * 1016 * <p> The {@code target} parameter is the target of the link. It may be an 1017 * {@link Path#isAbsolute absolute} or relative path and may not exist. When 1018 * the target is a relative path then file system operations on the resulting 1019 * link are relative to the path of the link. 1020 * 1021 * <p> The {@code attrs} parameter is optional {@link FileAttribute 1022 * attributes} to set atomically when creating the link. Each attribute is 1023 * identified by its {@link FileAttribute#name name}. If more than one attribute 1024 * of the same name is included in the array then all but the last occurrence 1025 * is ignored. 1026 * 1027 * <p> Where symbolic links are supported, but the underlying {@link FileStore} 1028 * does not support symbolic links, then this may fail with an {@link 1029 * IOException}. Additionally, some operating systems may require that the 1030 * Java virtual machine be started with implementation specific privileges to 1031 * create symbolic links, in which case this method may throw {@code IOException}. 1032 * 1033 * @param link 1034 * the path of the symbolic link to create 1035 * @param target 1036 * the target of the symbolic link 1037 * @param attrs 1038 * the array of attributes to set atomically when creating the 1039 * symbolic link 1040 * 1041 * @return the path to the symbolic link 1042 * 1043 * @throws UnsupportedOperationException 1044 * if the implementation does not support symbolic links or the 1045 * array contains an attribute that cannot be set atomically when 1046 * creating the symbolic link 1047 * @throws FileAlreadyExistsException 1048 * if a file with the name already exists <i>(optional specific 1049 * exception)</i> 1050 * @throws IOException 1051 * if an I/O error occurs 1052 * @throws SecurityException 1053 * In the case of the default provider, and a security manager 1054 * is installed, it denies {@link LinkPermission}{@code ("symbolic")} 1055 * or its {@link SecurityManager#checkWrite(String) checkWrite} 1056 * method denies write access to the path of the symbolic link. 1057 */ 1058 public static Path createSymbolicLink(Path link, Path target, 1059 FileAttribute<?>... attrs) 1060 throws IOException 1061 { 1062 provider(link).createSymbolicLink(link, target, attrs); 1063 return link; 1064 } 1065 1066 /** 1067 * Creates a new link (directory entry) for an existing file <i>(optional 1068 * operation)</i>. 1069 * 1070 * <p> The {@code link} parameter locates the directory entry to create. 1071 * The {@code existing} parameter is the path to an existing file. This 1072 * method creates a new directory entry for the file so that it can be 1073 * accessed using {@code link} as the path. On some file systems this is 1074 * known as creating a "hard link". Whether the file attributes are 1075 * maintained for the file or for each directory entry is file system 1076 * specific and therefore not specified. Typically, a file system requires 1077 * that all links (directory entries) for a file be on the same file system. 1078 * Furthermore, on some platforms, the Java virtual machine may require to 1079 * be started with implementation specific privileges to create hard links 1080 * or to create links to directories. 1081 * 1082 * @param link 1083 * the link (directory entry) to create 1084 * @param existing 1085 * a path to an existing file 1086 * 1087 * @return the path to the link (directory entry) 1088 * 1089 * @throws UnsupportedOperationException 1090 * if the implementation does not support adding an existing file 1091 * to a directory 1092 * @throws FileAlreadyExistsException 1093 * if the entry could not otherwise be created because a file of 1094 * that name already exists <i>(optional specific exception)</i> 1095 * @throws IOException 1096 * if an I/O error occurs 1097 * @throws SecurityException 1098 * In the case of the default provider, and a security manager 1099 * is installed, it denies {@link LinkPermission}{@code ("hard")} 1100 * or its {@link SecurityManager#checkWrite(String) checkWrite} 1101 * method denies write access to either the link or the 1102 * existing file. 1103 */ 1104 public static Path createLink(Path link, Path existing) throws IOException { 1105 provider(link).createLink(link, existing); 1106 return link; 1107 } 1108 1109 /** 1110 * Deletes a file. 1111 * 1112 * <p> An implementation may require to examine the file to determine if the 1113 * file is a directory. Consequently this method may not be atomic with respect 1114 * to other file system operations. If the file is a symbolic link then the 1115 * symbolic link itself, not the final target of the link, is deleted. 1116 * 1117 * <p> If the file is a directory then the directory must be empty. In some 1118 * implementations a directory has entries for special files or links that 1119 * are created when the directory is created. In such implementations a 1120 * directory is considered empty when only the special entries exist. 1121 * This method can be used with the {@link #walkFileTree walkFileTree} 1122 * method to delete a directory and all entries in the directory, or an 1123 * entire <i>file-tree</i> where required. 1124 * 1125 * <p> On some operating systems it may not be possible to remove a file when 1126 * it is open and in use by this Java virtual machine or other programs. 1127 * 1128 * @param path 1129 * the path to the file to delete 1130 * 1131 * @throws NoSuchFileException 1132 * if the file does not exist <i>(optional specific exception)</i> 1133 * @throws DirectoryNotEmptyException 1134 * if the file is a directory and could not otherwise be deleted 1135 * because the directory is not empty <i>(optional specific 1136 * exception)</i> 1137 * @throws IOException 1138 * if an I/O error occurs 1139 * @throws SecurityException 1140 * In the case of the default provider, and a security manager is 1141 * installed, the {@link SecurityManager#checkDelete(String)} method 1142 * is invoked to check delete access to the file 1143 */ 1144 public static void delete(Path path) throws IOException { 1145 provider(path).delete(path); 1146 } 1147 1148 /** 1149 * Deletes a file if it exists. 1150 * 1151 * <p> As with the {@link #delete(Path) delete(Path)} method, an 1152 * implementation may need to examine the file to determine if the file is a 1153 * directory. Consequently this method may not be atomic with respect to 1154 * other file system operations. If the file is a symbolic link, then the 1155 * symbolic link itself, not the final target of the link, is deleted. 1156 * 1157 * <p> If the file is a directory then the directory must be empty. In some 1158 * implementations a directory has entries for special files or links that 1159 * are created when the directory is created. In such implementations a 1160 * directory is considered empty when only the special entries exist. 1161 * 1162 * <p> On some operating systems it may not be possible to remove a file when 1163 * it is open and in use by this Java virtual machine or other programs. 1164 * 1165 * @param path 1166 * the path to the file to delete 1167 * 1168 * @return {@code true} if the file was deleted by this method; {@code 1169 * false} if the file could not be deleted because it did not 1170 * exist 1171 * 1172 * @throws DirectoryNotEmptyException 1173 * if the file is a directory and could not otherwise be deleted 1174 * because the directory is not empty <i>(optional specific 1175 * exception)</i> 1176 * @throws IOException 1177 * if an I/O error occurs 1178 * @throws SecurityException 1179 * In the case of the default provider, and a security manager is 1180 * installed, the {@link SecurityManager#checkDelete(String)} method 1181 * is invoked to check delete access to the file. 1182 */ 1183 public static boolean deleteIfExists(Path path) throws IOException { 1184 return provider(path).deleteIfExists(path); 1185 } 1186 1187 // -- Copying and moving files -- 1188 1189 /** 1190 * Copy a file to a target file. 1191 * 1192 * <p> This method copies a file to the target file with the {@code 1193 * options} parameter specifying how the copy is performed. By default, the 1194 * copy fails if the target file already exists or is a symbolic link, 1195 * except if the source and target are the {@link #isSameFile same} file, in 1196 * which case the method completes without copying the file. File attributes 1197 * are not required to be copied to the target file. If symbolic links are 1198 * supported, and the file is a symbolic link, then the final target of the 1199 * link is copied. If the file is a directory then it creates an empty 1200 * directory in the target location (entries in the directory are not 1201 * copied). This method can be used with the {@link #walkFileTree 1202 * walkFileTree} method to copy a directory and all entries in the directory, 1203 * or an entire <i>file-tree</i> where required. 1204 * 1205 * <p> The {@code options} parameter may include any of the following: 1206 * 1207 * <table class="striped"> 1208 * <caption style="display:none">Options</caption> 1209 * <thead> 1210 * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> 1211 * </thead> 1212 * <tbody> 1213 * <tr> 1214 * <th scope="row"> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </th> 1215 * <td> If the target file exists, then the target file is replaced if it 1216 * is not a non-empty directory. If the target file exists and is a 1217 * symbolic link, then the symbolic link itself, not the target of 1218 * the link, is replaced. </td> 1219 * </tr> 1220 * <tr> 1221 * <th scope="row"> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </th> 1222 * <td> Attempts to copy the file attributes associated with this file to 1223 * the target file. The exact file attributes that are copied is platform 1224 * and file system dependent and therefore unspecified. Minimally, the 1225 * {@link BasicFileAttributes#lastModifiedTime last-modified-time} is 1226 * copied to the target file if supported by both the source and target 1227 * file stores. Copying of file timestamps may result in precision 1228 * loss. </td> 1229 * </tr> 1230 * <tr> 1231 * <th scope="row"> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </th> 1232 * <td> Symbolic links are not followed. If the file is a symbolic link, 1233 * then the symbolic link itself, not the target of the link, is copied. 1234 * It is implementation specific if file attributes can be copied to the 1235 * new link. In other words, the {@code COPY_ATTRIBUTES} option may be 1236 * ignored when copying a symbolic link. </td> 1237 * </tr> 1238 * </tbody> 1239 * </table> 1240 * 1241 * <p> An implementation of this interface may support additional 1242 * implementation specific options. 1243 * 1244 * <p> Copying a file is not an atomic operation. If an {@link IOException} 1245 * is thrown, then it is possible that the target file is incomplete or some 1246 * of its file attributes have not been copied from the source file. When 1247 * the {@code REPLACE_EXISTING} option is specified and the target file 1248 * exists, then the target file is replaced. The check for the existence of 1249 * the file and the creation of the new file may not be atomic with respect 1250 * to other file system activities. 1251 * 1252 * <p> <b>Usage Example:</b> 1253 * Suppose we want to copy a file into a directory, giving it the same file 1254 * name as the source file: 1255 * <pre> 1256 * Path source = ... 1257 * Path newdir = ... 1258 * Files.copy(source, newdir.resolve(source.getFileName()); 1259 * </pre> 1260 * 1261 * @param source 1262 * the path to the file to copy 1263 * @param target 1264 * the path to the target file (may be associated with a different 1265 * provider to the source path) 1266 * @param options 1267 * options specifying how the copy should be done 1268 * 1269 * @return the path to the target file 1270 * 1271 * @throws UnsupportedOperationException 1272 * if the array contains a copy option that is not supported 1273 * @throws FileAlreadyExistsException 1274 * if the target file exists but cannot be replaced because the 1275 * {@code REPLACE_EXISTING} option is not specified <i>(optional 1276 * specific exception)</i> 1277 * @throws DirectoryNotEmptyException 1278 * the {@code REPLACE_EXISTING} option is specified but the file 1279 * cannot be replaced because it is a non-empty directory 1280 * <i>(optional specific exception)</i> 1281 * @throws IOException 1282 * if an I/O error occurs 1283 * @throws SecurityException 1284 * In the case of the default provider, and a security manager is 1285 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1286 * method is invoked to check read access to the source file, the 1287 * {@link SecurityManager#checkWrite(String) checkWrite} is invoked 1288 * to check write access to the target file. If a symbolic link is 1289 * copied the security manager is invoked to check {@link 1290 * LinkPermission}{@code ("symbolic")}. 1291 */ 1292 public static Path copy(Path source, Path target, CopyOption... options) 1293 throws IOException 1294 { 1295 FileSystemProvider provider = provider(source); 1296 if (provider(target) == provider) { 1297 // same provider 1298 provider.copy(source, target, options); 1299 } else { 1300 // different providers 1301 CopyMoveHelper.copyToForeignTarget(source, target, options); 1302 } 1303 return target; 1304 } 1305 1306 /** 1307 * Move or rename a file to a target file. 1308 * 1309 * <p> By default, this method attempts to move the file to the target 1310 * file, failing if the target file exists except if the source and 1311 * target are the {@link #isSameFile same} file, in which case this method 1312 * has no effect. If the file is a symbolic link then the symbolic link 1313 * itself, not the target of the link, is moved. This method may be 1314 * invoked to move an empty directory. In some implementations a directory 1315 * has entries for special files or links that are created when the 1316 * directory is created. In such implementations a directory is considered 1317 * empty when only the special entries exist. When invoked to move a 1318 * directory that is not empty then the directory is moved if it does not 1319 * require moving the entries in the directory. For example, renaming a 1320 * directory on the same {@link FileStore} will usually not require moving 1321 * the entries in the directory. When moving a directory requires that its 1322 * entries be moved then this method fails (by throwing an {@code 1323 * IOException}). To move a <i>file tree</i> may involve copying rather 1324 * than moving directories and this can be done using the {@link 1325 * #copy copy} method in conjunction with the {@link 1326 * #walkFileTree Files.walkFileTree} utility method. 1327 * 1328 * <p> The {@code options} parameter may include any of the following: 1329 * 1330 * <table class="striped"> 1331 * <caption style="display:none">Options</caption> 1332 * <thead> 1333 * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> 1334 * </thead> 1335 * <tbody> 1336 * <tr> 1337 * <th scope="row"> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </th> 1338 * <td> If the target file exists, then the target file is replaced if it 1339 * is not a non-empty directory. If the target file exists and is a 1340 * symbolic link, then the symbolic link itself, not the target of 1341 * the link, is replaced. </td> 1342 * </tr> 1343 * <tr> 1344 * <th scope="row"> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </th> 1345 * <td> The move is performed as an atomic file system operation and all 1346 * other options are ignored. If the target file exists then it is 1347 * implementation specific if the existing file is replaced or this method 1348 * fails by throwing an {@link IOException}. If the move cannot be 1349 * performed as an atomic file system operation then {@link 1350 * AtomicMoveNotSupportedException} is thrown. This can arise, for 1351 * example, when the target location is on a different {@code FileStore} 1352 * and would require that the file be copied, or target location is 1353 * associated with a different provider to this object. </td> 1354 * </tbody> 1355 * </table> 1356 * 1357 * <p> An implementation of this interface may support additional 1358 * implementation specific options. 1359 * 1360 * <p> Moving a file will copy the {@link 1361 * BasicFileAttributes#lastModifiedTime last-modified-time} to the target 1362 * file if supported by both source and target file stores. Copying of file 1363 * timestamps may result in precision loss. An implementation may also 1364 * attempt to copy other file attributes but is not required to fail if the 1365 * file attributes cannot be copied. When the move is performed as 1366 * a non-atomic operation, and an {@code IOException} is thrown, then the 1367 * state of the files is not defined. The original file and the target file 1368 * may both exist, the target file may be incomplete or some of its file 1369 * attributes may not been copied from the original file. 1370 * 1371 * <p> <b>Usage Examples:</b> 1372 * Suppose we want to rename a file to "newname", keeping the file in the 1373 * same directory: 1374 * <pre> 1375 * Path source = ... 1376 * Files.move(source, source.resolveSibling("newname")); 1377 * </pre> 1378 * Alternatively, suppose we want to move a file to new directory, keeping 1379 * the same file name, and replacing any existing file of that name in the 1380 * directory: 1381 * <pre> 1382 * Path source = ... 1383 * Path newdir = ... 1384 * Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING); 1385 * </pre> 1386 * 1387 * @param source 1388 * the path to the file to move 1389 * @param target 1390 * the path to the target file (may be associated with a different 1391 * provider to the source path) 1392 * @param options 1393 * options specifying how the move should be done 1394 * 1395 * @return the path to the target file 1396 * 1397 * @throws UnsupportedOperationException 1398 * if the array contains a copy option that is not supported 1399 * @throws FileAlreadyExistsException 1400 * if the target file exists but cannot be replaced because the 1401 * {@code REPLACE_EXISTING} option is not specified <i>(optional 1402 * specific exception)</i> 1403 * @throws DirectoryNotEmptyException 1404 * the {@code REPLACE_EXISTING} option is specified but the file 1405 * cannot be replaced because it is a non-empty directory, or the 1406 * source is a non-empty directory containing entries that would 1407 * be required to be moved <i>(optional specific exceptions)</i> 1408 * @throws AtomicMoveNotSupportedException 1409 * if the options array contains the {@code ATOMIC_MOVE} option but 1410 * the file cannot be moved as an atomic file system operation. 1411 * @throws IOException 1412 * if an I/O error occurs 1413 * @throws SecurityException 1414 * In the case of the default provider, and a security manager is 1415 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 1416 * method is invoked to check write access to both the source and 1417 * target file. 1418 */ 1419 public static Path move(Path source, Path target, CopyOption... options) 1420 throws IOException 1421 { 1422 FileSystemProvider provider = provider(source); 1423 if (provider(target) == provider) { 1424 // same provider 1425 provider.move(source, target, options); 1426 } else { 1427 // different providers 1428 CopyMoveHelper.moveToForeignTarget(source, target, options); 1429 } 1430 return target; 1431 } 1432 1433 // -- Miscellaneous -- 1434 1435 /** 1436 * Reads the target of a symbolic link <i>(optional operation)</i>. 1437 * 1438 * <p> If the file system supports <a href="package-summary.html#links">symbolic 1439 * links</a> then this method is used to read the target of the link, failing 1440 * if the file is not a symbolic link. The target of the link need not exist. 1441 * The returned {@code Path} object will be associated with the same file 1442 * system as {@code link}. 1443 * 1444 * @param link 1445 * the path to the symbolic link 1446 * 1447 * @return a {@code Path} object representing the target of the link 1448 * 1449 * @throws UnsupportedOperationException 1450 * if the implementation does not support symbolic links 1451 * @throws NotLinkException 1452 * if the target could otherwise not be read because the file 1453 * is not a symbolic link <i>(optional specific exception)</i> 1454 * @throws IOException 1455 * if an I/O error occurs 1456 * @throws SecurityException 1457 * In the case of the default provider, and a security manager 1458 * is installed, it checks that {@code FilePermission} has been 1459 * granted with the "{@code readlink}" action to read the link. 1460 */ 1461 public static Path readSymbolicLink(Path link) throws IOException { 1462 return provider(link).readSymbolicLink(link); 1463 } 1464 1465 /** 1466 * Returns the {@link FileStore} representing the file store where a file 1467 * is located. 1468 * 1469 * <p> Once a reference to the {@code FileStore} is obtained it is 1470 * implementation specific if operations on the returned {@code FileStore}, 1471 * or {@link FileStoreAttributeView} objects obtained from it, continue 1472 * to depend on the existence of the file. In particular the behavior is not 1473 * defined for the case that the file is deleted or moved to a different 1474 * file store. 1475 * 1476 * @param path 1477 * the path to the file 1478 * 1479 * @return the file store where the file is stored 1480 * 1481 * @throws IOException 1482 * if an I/O error occurs 1483 * @throws SecurityException 1484 * In the case of the default provider, and a security manager is 1485 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1486 * method is invoked to check read access to the file, and in 1487 * addition it checks 1488 * {@link RuntimePermission}{@code ("getFileStoreAttributes")} 1489 */ 1490 public static FileStore getFileStore(Path path) throws IOException { 1491 return provider(path).getFileStore(path); 1492 } 1493 1494 /** 1495 * Tests if two paths locate the same file. 1496 * 1497 * <p> If both {@code Path} objects are {@link Path#equals(Object) equal} 1498 * then this method returns {@code true} without checking if the file exists. 1499 * If the two {@code Path} objects are associated with different providers 1500 * then this method returns {@code false}. Otherwise, this method checks if 1501 * both {@code Path} objects locate the same file, and depending on the 1502 * implementation, may require to open or access both files. 1503 * 1504 * <p> If the file system and files remain static, then this method implements 1505 * an equivalence relation for non-null {@code Paths}. 1506 * <ul> 1507 * <li>It is <i>reflexive</i>: for {@code Path} {@code f}, 1508 * {@code isSameFile(f,f)} should return {@code true}. 1509 * <li>It is <i>symmetric</i>: for two {@code Paths} {@code f} and {@code g}, 1510 * {@code isSameFile(f,g)} will equal {@code isSameFile(g,f)}. 1511 * <li>It is <i>transitive</i>: for three {@code Paths} 1512 * {@code f}, {@code g}, and {@code h}, if {@code isSameFile(f,g)} returns 1513 * {@code true} and {@code isSameFile(g,h)} returns {@code true}, then 1514 * {@code isSameFile(f,h)} will return {@code true}. 1515 * </ul> 1516 * 1517 * @param path 1518 * one path to the file 1519 * @param path2 1520 * the other path 1521 * 1522 * @return {@code true} if, and only if, the two paths locate the same file 1523 * 1524 * @throws IOException 1525 * if an I/O error occurs 1526 * @throws SecurityException 1527 * In the case of the default provider, and a security manager is 1528 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1529 * method is invoked to check read access to both files. 1530 * 1531 * @see java.nio.file.attribute.BasicFileAttributes#fileKey 1532 */ 1533 public static boolean isSameFile(Path path, Path path2) throws IOException { 1534 return provider(path).isSameFile(path, path2); 1535 } 1536 1537 /** 1538 * Finds and returns the position of the first mismatched byte in the content 1539 * of two files, or {@code -1L} if there is no mismatch. The position will be 1540 * in the inclusive range of {@code 0L} up to the size (in bytes) of the 1541 * smaller file. 1542 * 1543 * <p> Two files are considered to match if they satisfy one of the following 1544 * conditions: 1545 * <ul> 1546 * <li> The two paths locate the {@linkplain #isSameFile(Path, Path) same file}, 1547 * even if two {@linkplain Path#equals(Object) equal} paths locate a file 1548 * does not exist, or </li> 1549 * <li> The two files are the same size, and every byte in the first file 1550 * is identical to the corresponding byte in the second file. </li> 1551 * </ul> 1552 * 1553 * <p> Otherwise there is a mismatch between the two files and the value 1554 * returned by this method is: 1555 * <ul> 1556 * <li> The position of the first mismatched byte, or </li> 1557 * <li> The size of the smaller file (in bytes) when the files are different 1558 * sizes and every byte of the smaller file is identical to the 1559 * corresponding byte of the larger file. </li> 1560 * </ul> 1561 * 1562 * <p> This method may not be atomic with respect to other file system 1563 * operations. This method is always <i>reflexive</i> (for {@code Path f}, 1564 * {@code mismatch(f,f)} returns {@code -1L}). If the file system and files 1565 * remain static, then this method is <i>symmetric</i> (for two {@code Paths f} 1566 * and {@code g}, {@code mismatch(f,g)} will return the same value as 1567 * {@code mismatch(g,f)}). 1568 * 1569 * @param path 1570 * the path to the first file 1571 * @param path2 1572 * the path to the second file 1573 * 1574 * @return the position of the first mismatch or {@code -1L} if no mismatch 1575 * 1576 * @throws IOException 1577 * if an I/O error occurs 1578 * @throws SecurityException 1579 * In the case of the default provider, and a security manager is 1580 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1581 * method is invoked to check read access to both files. 1582 * 1583 * @since 12 1584 */ 1585 public static long mismatch(Path path, Path path2) throws IOException { 1586 if (isSameFile(path, path2)) { 1587 return -1; 1588 } 1589 byte[] buffer1 = new byte[BUFFER_SIZE]; 1590 byte[] buffer2 = new byte[BUFFER_SIZE]; 1591 try (InputStream in1 = Files.newInputStream(path); 1592 InputStream in2 = Files.newInputStream(path2);) { 1593 long totalRead = 0; 1594 while (true) { 1595 int nRead1 = in1.readNBytes(buffer1, 0, BUFFER_SIZE); 1596 int nRead2 = in2.readNBytes(buffer2, 0, BUFFER_SIZE); 1597 1598 int i = Arrays.mismatch(buffer1, 0, nRead1, buffer2, 0, nRead2); 1599 if (i > -1) { 1600 return totalRead + i; 1601 } 1602 if (nRead1 < BUFFER_SIZE) { 1603 // we've reached the end of the files, but found no mismatch 1604 return -1; 1605 } 1606 totalRead += nRead1; 1607 } 1608 } 1609 } 1610 1611 /** 1612 * Tells whether or not a file is considered <em>hidden</em>. 1613 * 1614 * @apiNote 1615 * The exact definition of hidden is platform or provider dependent. On UNIX 1616 * for example a file is considered to be hidden if its name begins with a 1617 * period character ('.'). On Windows a file is considered hidden if the DOS 1618 * {@link DosFileAttributes#isHidden hidden} attribute is set. 1619 * 1620 * <p> Depending on the implementation this method may require to access 1621 * the file system to determine if the file is considered hidden. 1622 * 1623 * @param path 1624 * the path to the file to test 1625 * 1626 * @return {@code true} if the file is considered hidden 1627 * 1628 * @throws IOException 1629 * if an I/O error occurs 1630 * @throws SecurityException 1631 * In the case of the default provider, and a security manager is 1632 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1633 * method is invoked to check read access to the file. 1634 */ 1635 public static boolean isHidden(Path path) throws IOException { 1636 return provider(path).isHidden(path); 1637 } 1638 1639 // lazy loading of default and installed file type detectors 1640 private static class FileTypeDetectors{ 1641 static final FileTypeDetector defaultFileTypeDetector = 1642 createDefaultFileTypeDetector(); 1643 static final List<FileTypeDetector> installedDetectors = 1644 loadInstalledDetectors(); 1645 1646 // creates the default file type detector 1647 private static FileTypeDetector createDefaultFileTypeDetector() { 1648 return AccessController 1649 .doPrivileged(new PrivilegedAction<>() { 1650 @Override public FileTypeDetector run() { 1651 return sun.nio.fs.DefaultFileTypeDetector.create(); 1652 }}); 1653 } 1654 1655 // loads all installed file type detectors 1656 private static List<FileTypeDetector> loadInstalledDetectors() { 1657 return AccessController 1658 .doPrivileged(new PrivilegedAction<>() { 1659 @Override public List<FileTypeDetector> run() { 1660 List<FileTypeDetector> list = new ArrayList<>(); 1661 ServiceLoader<FileTypeDetector> loader = ServiceLoader 1662 .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader()); 1663 for (FileTypeDetector detector: loader) { 1664 list.add(detector); 1665 } 1666 return list; 1667 }}); 1668 } 1669 } 1670 1671 /** 1672 * Probes the content type of a file. 1673 * 1674 * <p> This method uses the installed {@link FileTypeDetector} implementations 1675 * to probe the given file to determine its content type. Each file type 1676 * detector's {@link FileTypeDetector#probeContentType probeContentType} is 1677 * invoked, in turn, to probe the file type. If the file is recognized then 1678 * the content type is returned. If the file is not recognized by any of the 1679 * installed file type detectors then a system-default file type detector is 1680 * invoked to guess the content type. 1681 * 1682 * <p> A given invocation of the Java virtual machine maintains a system-wide 1683 * list of file type detectors. Installed file type detectors are loaded 1684 * using the service-provider loading facility defined by the {@link ServiceLoader} 1685 * class. Installed file type detectors are loaded using the system class 1686 * loader. If the system class loader cannot be found then the platform class 1687 * loader is used. File type detectors are typically installed 1688 * by placing them in a JAR file on the application class path, 1689 * the JAR file contains a provider-configuration file 1690 * named {@code java.nio.file.spi.FileTypeDetector} in the resource directory 1691 * {@code META-INF/services}, and the file lists one or more fully-qualified 1692 * names of concrete subclass of {@code FileTypeDetector } that have a zero 1693 * argument constructor. If the process of locating or instantiating the 1694 * installed file type detectors fails then an unspecified error is thrown. 1695 * The ordering that installed providers are located is implementation 1696 * specific. 1697 * 1698 * <p> The return value of this method is the string form of the value of a 1699 * Multipurpose Internet Mail Extension (MIME) content type as 1700 * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: 1701 * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet 1702 * Message Bodies</i></a>. The string is guaranteed to be parsable according 1703 * to the grammar in the RFC. 1704 * 1705 * @param path 1706 * the path to the file to probe 1707 * 1708 * @return The content type of the file, or {@code null} if the content 1709 * type cannot be determined 1710 * 1711 * @throws IOException 1712 * if an I/O error occurs 1713 * @throws SecurityException 1714 * If a security manager is installed and it denies an unspecified 1715 * permission required by a file type detector implementation. 1716 */ 1717 public static String probeContentType(Path path) 1718 throws IOException 1719 { 1720 // try installed file type detectors 1721 for (FileTypeDetector detector: FileTypeDetectors.installedDetectors) { 1722 String result = detector.probeContentType(path); 1723 if (result != null) 1724 return result; 1725 } 1726 1727 // fallback to default 1728 return FileTypeDetectors.defaultFileTypeDetector.probeContentType(path); 1729 } 1730 1731 // -- File Attributes -- 1732 1733 /** 1734 * Returns a file attribute view of a given type. 1735 * 1736 * <p> A file attribute view provides a read-only or updatable view of a 1737 * set of file attributes. This method is intended to be used where the file 1738 * attribute view defines type-safe methods to read or update the file 1739 * attributes. The {@code type} parameter is the type of the attribute view 1740 * required and the method returns an instance of that type if supported. 1741 * The {@link BasicFileAttributeView} type supports access to the basic 1742 * attributes of a file. Invoking this method to select a file attribute 1743 * view of that type will always return an instance of that class. 1744 * 1745 * <p> The {@code options} array may be used to indicate how symbolic links 1746 * are handled by the resulting file attribute view for the case that the 1747 * file is a symbolic link. By default, symbolic links are followed. If the 1748 * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then 1749 * symbolic links are not followed. This option is ignored by implementations 1750 * that do not support symbolic links. 1751 * 1752 * <p> <b>Usage Example:</b> 1753 * Suppose we want read or set a file's ACL, if supported: 1754 * <pre> 1755 * Path path = ... 1756 * AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); 1757 * if (view != null) { 1758 * List<AclEntry> acl = view.getAcl(); 1759 * : 1760 * } 1761 * </pre> 1762 * 1763 * @param <V> 1764 * The {@code FileAttributeView} type 1765 * @param path 1766 * the path to the file 1767 * @param type 1768 * the {@code Class} object corresponding to the file attribute view 1769 * @param options 1770 * options indicating how symbolic links are handled 1771 * 1772 * @return a file attribute view of the specified type, or {@code null} if 1773 * the attribute view type is not available 1774 */ 1775 public static <V extends FileAttributeView> V getFileAttributeView(Path path, 1776 Class<V> type, 1777 LinkOption... options) 1778 { 1779 return provider(path).getFileAttributeView(path, type, options); 1780 } 1781 1782 /** 1783 * Reads a file's attributes as a bulk operation. 1784 * 1785 * <p> The {@code type} parameter is the type of the attributes required 1786 * and this method returns an instance of that type if supported. All 1787 * implementations support a basic set of file attributes and so invoking 1788 * this method with a {@code type} parameter of {@code 1789 * BasicFileAttributes.class} will not throw {@code 1790 * UnsupportedOperationException}. 1791 * 1792 * <p> The {@code options} array may be used to indicate how symbolic links 1793 * are handled for the case that the file is a symbolic link. By default, 1794 * symbolic links are followed and the file attribute of the final target 1795 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1796 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1797 * 1798 * <p> It is implementation specific if all file attributes are read as an 1799 * atomic operation with respect to other file system operations. 1800 * 1801 * <p> <b>Usage Example:</b> 1802 * Suppose we want to read a file's attributes in bulk: 1803 * <pre> 1804 * Path path = ... 1805 * BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 1806 * </pre> 1807 * Alternatively, suppose we want to read file's POSIX attributes without 1808 * following symbolic links: 1809 * <pre> 1810 * PosixFileAttributes attrs = 1811 * Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS); 1812 * </pre> 1813 * 1814 * @param <A> 1815 * The {@code BasicFileAttributes} type 1816 * @param path 1817 * the path to the file 1818 * @param type 1819 * the {@code Class} of the file attributes required 1820 * to read 1821 * @param options 1822 * options indicating how symbolic links are handled 1823 * 1824 * @return the file attributes 1825 * 1826 * @throws UnsupportedOperationException 1827 * if an attributes of the given type are not supported 1828 * @throws IOException 1829 * if an I/O error occurs 1830 * @throws SecurityException 1831 * In the case of the default provider, a security manager is 1832 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1833 * method is invoked to check read access to the file. If this 1834 * method is invoked to read security sensitive attributes then the 1835 * security manager may be invoke to check for additional permissions. 1836 */ 1837 public static <A extends BasicFileAttributes> A readAttributes(Path path, 1838 Class<A> type, 1839 LinkOption... options) 1840 throws IOException 1841 { 1842 return provider(path).readAttributes(path, type, options); 1843 } 1844 1845 /** 1846 * Sets the value of a file attribute. 1847 * 1848 * <p> The {@code attribute} parameter identifies the attribute to be set 1849 * and takes the form: 1850 * <blockquote> 1851 * [<i>view-name</i><b>:</b>]<i>attribute-name</i> 1852 * </blockquote> 1853 * where square brackets [...] delineate an optional component and the 1854 * character {@code ':'} stands for itself. 1855 * 1856 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1857 * FileAttributeView} that identifies a set of file attributes. If not 1858 * specified then it defaults to {@code "basic"}, the name of the file 1859 * attribute view that identifies the basic set of file attributes common to 1860 * many file systems. <i>attribute-name</i> is the name of the attribute 1861 * within the set. 1862 * 1863 * <p> The {@code options} array may be used to indicate how symbolic links 1864 * are handled for the case that the file is a symbolic link. By default, 1865 * symbolic links are followed and the file attribute of the final target 1866 * of the link is set. If the option {@link LinkOption#NOFOLLOW_LINKS 1867 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1868 * 1869 * <p> <b>Usage Example:</b> 1870 * Suppose we want to set the DOS "hidden" attribute: 1871 * <pre> 1872 * Path path = ... 1873 * Files.setAttribute(path, "dos:hidden", true); 1874 * </pre> 1875 * 1876 * @param path 1877 * the path to the file 1878 * @param attribute 1879 * the attribute to set 1880 * @param value 1881 * the attribute value 1882 * @param options 1883 * options indicating how symbolic links are handled 1884 * 1885 * @return the given path 1886 * 1887 * @throws UnsupportedOperationException 1888 * if the attribute view is not available 1889 * @throws IllegalArgumentException 1890 * if the attribute name is not specified, or is not recognized, or 1891 * the attribute value is of the correct type but has an 1892 * inappropriate value 1893 * @throws ClassCastException 1894 * if the attribute value is not of the expected type or is a 1895 * collection containing elements that are not of the expected 1896 * type 1897 * @throws IOException 1898 * if an I/O error occurs 1899 * @throws SecurityException 1900 * In the case of the default provider, and a security manager is 1901 * installed, its {@link SecurityManager#checkWrite(String) checkWrite} 1902 * method denies write access to the file. If this method is invoked 1903 * to set security sensitive attributes then the security manager 1904 * may be invoked to check for additional permissions. 1905 */ 1906 public static Path setAttribute(Path path, String attribute, Object value, 1907 LinkOption... options) 1908 throws IOException 1909 { 1910 provider(path).setAttribute(path, attribute, value, options); 1911 return path; 1912 } 1913 1914 /** 1915 * Reads the value of a file attribute. 1916 * 1917 * <p> The {@code attribute} parameter identifies the attribute to be read 1918 * and takes the form: 1919 * <blockquote> 1920 * [<i>view-name</i><b>:</b>]<i>attribute-name</i> 1921 * </blockquote> 1922 * where square brackets [...] delineate an optional component and the 1923 * character {@code ':'} stands for itself. 1924 * 1925 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1926 * FileAttributeView} that identifies a set of file attributes. If not 1927 * specified then it defaults to {@code "basic"}, the name of the file 1928 * attribute view that identifies the basic set of file attributes common to 1929 * many file systems. <i>attribute-name</i> is the name of the attribute. 1930 * 1931 * <p> The {@code options} array may be used to indicate how symbolic links 1932 * are handled for the case that the file is a symbolic link. By default, 1933 * symbolic links are followed and the file attribute of the final target 1934 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1935 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1936 * 1937 * <p> <b>Usage Example:</b> 1938 * Suppose we require the user ID of the file owner on a system that 1939 * supports a "{@code unix}" view: 1940 * <pre> 1941 * Path path = ... 1942 * int uid = (Integer)Files.getAttribute(path, "unix:uid"); 1943 * </pre> 1944 * 1945 * @param path 1946 * the path to the file 1947 * @param attribute 1948 * the attribute to read 1949 * @param options 1950 * options indicating how symbolic links are handled 1951 * 1952 * @return the attribute value 1953 * 1954 * @throws UnsupportedOperationException 1955 * if the attribute view is not available 1956 * @throws IllegalArgumentException 1957 * if the attribute name is not specified or is not recognized 1958 * @throws IOException 1959 * if an I/O error occurs 1960 * @throws SecurityException 1961 * In the case of the default provider, and a security manager is 1962 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1963 * method denies read access to the file. If this method is invoked 1964 * to read security sensitive attributes then the security manager 1965 * may be invoked to check for additional permissions. 1966 */ 1967 public static Object getAttribute(Path path, String attribute, 1968 LinkOption... options) 1969 throws IOException 1970 { 1971 // only one attribute should be read 1972 if (attribute.indexOf('*') >= 0 || attribute.indexOf(',') >= 0) 1973 throw new IllegalArgumentException(attribute); 1974 Map<String,Object> map = readAttributes(path, attribute, options); 1975 assert map.size() == 1; 1976 String name; 1977 int pos = attribute.indexOf(':'); 1978 if (pos == -1) { 1979 name = attribute; 1980 } else { 1981 name = (pos == attribute.length()) ? "" : attribute.substring(pos+1); 1982 } 1983 return map.get(name); 1984 } 1985 1986 /** 1987 * Reads a set of file attributes as a bulk operation. 1988 * 1989 * <p> The {@code attributes} parameter identifies the attributes to be read 1990 * and takes the form: 1991 * <blockquote> 1992 * [<i>view-name</i><b>:</b>]<i>attribute-list</i> 1993 * </blockquote> 1994 * where square brackets [...] delineate an optional component and the 1995 * character {@code ':'} stands for itself. 1996 * 1997 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1998 * FileAttributeView} that identifies a set of file attributes. If not 1999 * specified then it defaults to {@code "basic"}, the name of the file 2000 * attribute view that identifies the basic set of file attributes common to 2001 * many file systems. 2002 * 2003 * <p> The <i>attribute-list</i> component is a comma separated list of 2004 * one or more names of attributes to read. If the list contains the value 2005 * {@code "*"} then all attributes are read. Attributes that are not supported 2006 * are ignored and will not be present in the returned map. It is 2007 * implementation specific if all attributes are read as an atomic operation 2008 * with respect to other file system operations. 2009 * 2010 * <p> The following examples demonstrate possible values for the {@code 2011 * attributes} parameter: 2012 * 2013 * <table class="striped" style="text-align: left; margin-left:2em"> 2014 * <caption style="display:none">Possible values</caption> 2015 * <thead> 2016 * <tr> 2017 * <th scope="col">Example 2018 * <th scope="col">Description 2019 * </thead> 2020 * <tbody> 2021 * <tr> 2022 * <th scope="row"> {@code "*"} </th> 2023 * <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td> 2024 * </tr> 2025 * <tr> 2026 * <th scope="row"> {@code "size,lastModifiedTime,lastAccessTime"} </th> 2027 * <td> Reads the file size, last modified time, and last access time 2028 * attributes. </td> 2029 * </tr> 2030 * <tr> 2031 * <th scope="row"> {@code "posix:*"} </th> 2032 * <td> Read all {@link PosixFileAttributes POSIX-file-attributes}. </td> 2033 * </tr> 2034 * <tr> 2035 * <th scope="row"> {@code "posix:permissions,owner,size"} </th> 2036 * <td> Reads the POSIX file permissions, owner, and file size. </td> 2037 * </tr> 2038 * </tbody> 2039 * </table> 2040 * 2041 * <p> The {@code options} array may be used to indicate how symbolic links 2042 * are handled for the case that the file is a symbolic link. By default, 2043 * symbolic links are followed and the file attribute of the final target 2044 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2045 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2046 * 2047 * @param path 2048 * the path to the file 2049 * @param attributes 2050 * the attributes to read 2051 * @param options 2052 * options indicating how symbolic links are handled 2053 * 2054 * @return a map of the attributes returned; The map's keys are the 2055 * attribute names, its values are the attribute values 2056 * 2057 * @throws UnsupportedOperationException 2058 * if the attribute view is not available 2059 * @throws IllegalArgumentException 2060 * if no attributes are specified or an unrecognized attribute is 2061 * specified 2062 * @throws IOException 2063 * if an I/O error occurs 2064 * @throws SecurityException 2065 * In the case of the default provider, and a security manager is 2066 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2067 * method denies read access to the file. If this method is invoked 2068 * to read security sensitive attributes then the security manager 2069 * may be invoke to check for additional permissions. 2070 */ 2071 public static Map<String,Object> readAttributes(Path path, String attributes, 2072 LinkOption... options) 2073 throws IOException 2074 { 2075 return provider(path).readAttributes(path, attributes, options); 2076 } 2077 2078 /** 2079 * Returns a file's POSIX file permissions. 2080 * 2081 * <p> The {@code path} parameter is associated with a {@code FileSystem} 2082 * that supports the {@link PosixFileAttributeView}. This attribute view 2083 * provides access to file attributes commonly associated with files on file 2084 * systems used by operating systems that implement the Portable Operating 2085 * System Interface (POSIX) family of standards. 2086 * 2087 * <p> The {@code options} array may be used to indicate how symbolic links 2088 * are handled for the case that the file is a symbolic link. By default, 2089 * symbolic links are followed and the file attribute of the final target 2090 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2091 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2092 * 2093 * @param path 2094 * the path to the file 2095 * @param options 2096 * options indicating how symbolic links are handled 2097 * 2098 * @return the file permissions 2099 * 2100 * @throws UnsupportedOperationException 2101 * if the associated file system does not support the {@code 2102 * PosixFileAttributeView} 2103 * @throws IOException 2104 * if an I/O error occurs 2105 * @throws SecurityException 2106 * In the case of the default provider, a security manager is 2107 * installed, and it denies 2108 * {@link RuntimePermission}{@code ("accessUserInformation")} 2109 * or its {@link SecurityManager#checkRead(String) checkRead} method 2110 * denies read access to the file. 2111 */ 2112 public static Set<PosixFilePermission> getPosixFilePermissions(Path path, 2113 LinkOption... options) 2114 throws IOException 2115 { 2116 return readAttributes(path, PosixFileAttributes.class, options).permissions(); 2117 } 2118 2119 /** 2120 * Sets a file's POSIX permissions. 2121 * 2122 * <p> The {@code path} parameter is associated with a {@code FileSystem} 2123 * that supports the {@link PosixFileAttributeView}. This attribute view 2124 * provides access to file attributes commonly associated with files on file 2125 * systems used by operating systems that implement the Portable Operating 2126 * System Interface (POSIX) family of standards. 2127 * 2128 * @param path 2129 * The path to the file 2130 * @param perms 2131 * The new set of permissions 2132 * 2133 * @return The given path 2134 * 2135 * @throws UnsupportedOperationException 2136 * if the associated file system does not support the {@code 2137 * PosixFileAttributeView} 2138 * @throws ClassCastException 2139 * if the sets contains elements that are not of type {@code 2140 * PosixFilePermission} 2141 * @throws IOException 2142 * if an I/O error occurs 2143 * @throws SecurityException 2144 * In the case of the default provider, and a security manager is 2145 * installed, it denies 2146 * {@link RuntimePermission}{@code ("accessUserInformation")} 2147 * or its {@link SecurityManager#checkWrite(String) checkWrite} 2148 * method denies write access to the file. 2149 */ 2150 public static Path setPosixFilePermissions(Path path, 2151 Set<PosixFilePermission> perms) 2152 throws IOException 2153 { 2154 PosixFileAttributeView view = 2155 getFileAttributeView(path, PosixFileAttributeView.class); 2156 if (view == null) 2157 throw new UnsupportedOperationException(); 2158 view.setPermissions(perms); 2159 return path; 2160 } 2161 2162 /** 2163 * Returns the owner of a file. 2164 * 2165 * <p> The {@code path} parameter is associated with a file system that 2166 * supports {@link FileOwnerAttributeView}. This file attribute view provides 2167 * access to a file attribute that is the owner of the file. 2168 * 2169 * @param path 2170 * The path to the file 2171 * @param options 2172 * options indicating how symbolic links are handled 2173 * 2174 * @return A user principal representing the owner of the file 2175 * 2176 * @throws UnsupportedOperationException 2177 * if the associated file system does not support the {@code 2178 * FileOwnerAttributeView} 2179 * @throws IOException 2180 * if an I/O error occurs 2181 * @throws SecurityException 2182 * In the case of the default provider, and a security manager is 2183 * installed, it denies 2184 * {@link RuntimePermission}{@code ("accessUserInformation")} 2185 * or its {@link SecurityManager#checkRead(String) checkRead} method 2186 * denies read access to the file. 2187 */ 2188 public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException { 2189 FileOwnerAttributeView view = 2190 getFileAttributeView(path, FileOwnerAttributeView.class, options); 2191 if (view == null) 2192 throw new UnsupportedOperationException(); 2193 return view.getOwner(); 2194 } 2195 2196 /** 2197 * Updates the file owner. 2198 * 2199 * <p> The {@code path} parameter is associated with a file system that 2200 * supports {@link FileOwnerAttributeView}. This file attribute view provides 2201 * access to a file attribute that is the owner of the file. 2202 * 2203 * <p> <b>Usage Example:</b> 2204 * Suppose we want to make "joe" the owner of a file: 2205 * <pre> 2206 * Path path = ... 2207 * UserPrincipalLookupService lookupService = 2208 * provider(path).getUserPrincipalLookupService(); 2209 * UserPrincipal joe = lookupService.lookupPrincipalByName("joe"); 2210 * Files.setOwner(path, joe); 2211 * </pre> 2212 * 2213 * @param path 2214 * The path to the file 2215 * @param owner 2216 * The new file owner 2217 * 2218 * @return The given path 2219 * 2220 * @throws UnsupportedOperationException 2221 * if the associated file system does not support the {@code 2222 * FileOwnerAttributeView} 2223 * @throws IOException 2224 * if an I/O error occurs 2225 * @throws SecurityException 2226 * In the case of the default provider, and a security manager is 2227 * installed, it denies 2228 * {@link RuntimePermission}{@code ("accessUserInformation")} 2229 * or its {@link SecurityManager#checkWrite(String) checkWrite} 2230 * method denies write access to the file. 2231 * 2232 * @see FileSystem#getUserPrincipalLookupService 2233 * @see java.nio.file.attribute.UserPrincipalLookupService 2234 */ 2235 public static Path setOwner(Path path, UserPrincipal owner) 2236 throws IOException 2237 { 2238 FileOwnerAttributeView view = 2239 getFileAttributeView(path, FileOwnerAttributeView.class); 2240 if (view == null) 2241 throw new UnsupportedOperationException(); 2242 view.setOwner(owner); 2243 return path; 2244 } 2245 2246 /** 2247 * Tests whether a file is a symbolic link. 2248 * 2249 * <p> Where it is required to distinguish an I/O exception from the case 2250 * that the file is not a symbolic link then the file attributes can be 2251 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2252 * readAttributes} method and the file type tested with the {@link 2253 * BasicFileAttributes#isSymbolicLink} method. 2254 * 2255 * @param path The path to the file 2256 * 2257 * @return {@code true} if the file is a symbolic link; {@code false} if 2258 * the file does not exist, is not a symbolic link, or it cannot 2259 * be determined if the file is a symbolic link or not. 2260 * 2261 * @throws SecurityException 2262 * In the case of the default provider, and a security manager is 2263 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2264 * method denies read access to the file. 2265 */ 2266 public static boolean isSymbolicLink(Path path) { 2267 try { 2268 return readAttributes(path, 2269 BasicFileAttributes.class, 2270 LinkOption.NOFOLLOW_LINKS).isSymbolicLink(); 2271 } catch (IOException ioe) { 2272 return false; 2273 } 2274 } 2275 2276 /** 2277 * Tests whether a file is a directory. 2278 * 2279 * <p> The {@code options} array may be used to indicate how symbolic links 2280 * are handled for the case that the file is a symbolic link. By default, 2281 * symbolic links are followed and the file attribute of the final target 2282 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2283 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2284 * 2285 * <p> Where it is required to distinguish an I/O exception from the case 2286 * that the file is not a directory then the file attributes can be 2287 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2288 * readAttributes} method and the file type tested with the {@link 2289 * BasicFileAttributes#isDirectory} method. 2290 * 2291 * @param path 2292 * the path to the file to test 2293 * @param options 2294 * options indicating how symbolic links are handled 2295 * 2296 * @return {@code true} if the file is a directory; {@code false} if 2297 * the file does not exist, is not a directory, or it cannot 2298 * be determined if the file is a directory or not. 2299 * 2300 * @throws SecurityException 2301 * In the case of the default provider, and a security manager is 2302 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2303 * method denies read access to the file. 2304 */ 2305 public static boolean isDirectory(Path path, LinkOption... options) { 2306 if (options.length == 0) { 2307 FileSystemProvider provider = provider(path); 2308 if (provider instanceof AbstractFileSystemProvider) 2309 return ((AbstractFileSystemProvider)provider).isDirectory(path); 2310 } 2311 2312 try { 2313 return readAttributes(path, BasicFileAttributes.class, options).isDirectory(); 2314 } catch (IOException ioe) { 2315 return false; 2316 } 2317 } 2318 2319 /** 2320 * Tests whether a file is a regular file with opaque content. 2321 * 2322 * <p> The {@code options} array may be used to indicate how symbolic links 2323 * are handled for the case that the file is a symbolic link. By default, 2324 * symbolic links are followed and the file attribute of the final target 2325 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2326 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2327 * 2328 * <p> Where it is required to distinguish an I/O exception from the case 2329 * that the file is not a regular file then the file attributes can be 2330 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2331 * readAttributes} method and the file type tested with the {@link 2332 * BasicFileAttributes#isRegularFile} method. 2333 * 2334 * @param path 2335 * the path to the file 2336 * @param options 2337 * options indicating how symbolic links are handled 2338 * 2339 * @return {@code true} if the file is a regular file; {@code false} if 2340 * the file does not exist, is not a regular file, or it 2341 * cannot be determined if the file is a regular file or not. 2342 * 2343 * @throws SecurityException 2344 * In the case of the default provider, and a security manager is 2345 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2346 * method denies read access to the file. 2347 */ 2348 public static boolean isRegularFile(Path path, LinkOption... options) { 2349 if (options.length == 0) { 2350 FileSystemProvider provider = provider(path); 2351 if (provider instanceof AbstractFileSystemProvider) 2352 return ((AbstractFileSystemProvider)provider).isRegularFile(path); 2353 } 2354 2355 try { 2356 return readAttributes(path, BasicFileAttributes.class, options).isRegularFile(); 2357 } catch (IOException ioe) { 2358 return false; 2359 } 2360 } 2361 2362 /** 2363 * Returns a file's last modified time. 2364 * 2365 * <p> The {@code options} array may be used to indicate how symbolic links 2366 * are handled for the case that the file is a symbolic link. By default, 2367 * symbolic links are followed and the file attribute of the final target 2368 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2369 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2370 * 2371 * @param path 2372 * the path to the file 2373 * @param options 2374 * options indicating how symbolic links are handled 2375 * 2376 * @return a {@code FileTime} representing the time the file was last 2377 * modified, or an implementation specific default when a time 2378 * stamp to indicate the time of last modification is not supported 2379 * by the file system 2380 * 2381 * @throws IOException 2382 * if an I/O error occurs 2383 * @throws SecurityException 2384 * In the case of the default provider, and a security manager is 2385 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2386 * method denies read access to the file. 2387 * 2388 * @see BasicFileAttributes#lastModifiedTime 2389 */ 2390 public static FileTime getLastModifiedTime(Path path, LinkOption... options) 2391 throws IOException 2392 { 2393 return readAttributes(path, BasicFileAttributes.class, options).lastModifiedTime(); 2394 } 2395 2396 /** 2397 * Updates a file's last modified time attribute. The file time is converted 2398 * to the epoch and precision supported by the file system. Converting from 2399 * finer to coarser granularities result in precision loss. The behavior of 2400 * this method when attempting to set the last modified time when it is not 2401 * supported by the file system or is outside the range supported by the 2402 * underlying file store is not defined. It may or not fail by throwing an 2403 * {@code IOException}. 2404 * 2405 * <p> <b>Usage Example:</b> 2406 * Suppose we want to set the last modified time to the current time: 2407 * <pre> 2408 * Path path = ... 2409 * FileTime now = FileTime.fromMillis(System.currentTimeMillis()); 2410 * Files.setLastModifiedTime(path, now); 2411 * </pre> 2412 * 2413 * @param path 2414 * the path to the file 2415 * @param time 2416 * the new last modified time 2417 * 2418 * @return the given path 2419 * 2420 * @throws IOException 2421 * if an I/O error occurs 2422 * @throws SecurityException 2423 * In the case of the default provider, and a security manager is 2424 * installed, its {@link SecurityManager#checkWrite(String) 2425 * checkWrite} method denies write access to the file. 2426 * 2427 * @see BasicFileAttributeView#setTimes 2428 */ 2429 public static Path setLastModifiedTime(Path path, FileTime time) 2430 throws IOException 2431 { 2432 getFileAttributeView(path, BasicFileAttributeView.class) 2433 .setTimes(Objects.requireNonNull(time), null, null); 2434 return path; 2435 } 2436 2437 /** 2438 * Returns the size of a file (in bytes). The size may differ from the 2439 * actual size on the file system due to compression, support for sparse 2440 * files, or other reasons. The size of files that are not {@link 2441 * #isRegularFile regular} files is implementation specific and 2442 * therefore unspecified. 2443 * 2444 * @param path 2445 * the path to the file 2446 * 2447 * @return the file size, in bytes 2448 * 2449 * @throws IOException 2450 * if an I/O error occurs 2451 * @throws SecurityException 2452 * In the case of the default provider, and a security manager is 2453 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2454 * method denies read access to the file. 2455 * 2456 * @see BasicFileAttributes#size 2457 */ 2458 public static long size(Path path) throws IOException { 2459 return readAttributes(path, BasicFileAttributes.class).size(); 2460 } 2461 2462 // -- Accessibility -- 2463 2464 /** 2465 * Returns {@code false} if NOFOLLOW_LINKS is present. 2466 */ 2467 private static boolean followLinks(LinkOption... options) { 2468 boolean followLinks = true; 2469 for (LinkOption opt: options) { 2470 if (opt == LinkOption.NOFOLLOW_LINKS) { 2471 followLinks = false; 2472 continue; 2473 } 2474 if (opt == null) 2475 throw new NullPointerException(); 2476 throw new AssertionError("Should not get here"); 2477 } 2478 return followLinks; 2479 } 2480 2481 /** 2482 * Tests whether a file exists. 2483 * 2484 * <p> The {@code options} parameter may be used to indicate how symbolic links 2485 * are handled for the case that the file is a symbolic link. By default, 2486 * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS 2487 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2488 * 2489 * <p> Note that the result of this method is immediately outdated. If this 2490 * method indicates the file exists then there is no guarantee that a 2491 * subsequent access will succeed. Care should be taken when using this 2492 * method in security sensitive applications. 2493 * 2494 * @param path 2495 * the path to the file to test 2496 * @param options 2497 * options indicating how symbolic links are handled 2498 * . 2499 * @return {@code true} if the file exists; {@code false} if the file does 2500 * not exist or its existence cannot be determined. 2501 * 2502 * @throws SecurityException 2503 * In the case of the default provider, the {@link 2504 * SecurityManager#checkRead(String)} is invoked to check 2505 * read access to the file. 2506 * 2507 * @see #notExists 2508 */ 2509 public static boolean exists(Path path, LinkOption... options) { 2510 if (options.length == 0) { 2511 FileSystemProvider provider = provider(path); 2512 if (provider instanceof AbstractFileSystemProvider) 2513 return ((AbstractFileSystemProvider)provider).exists(path); 2514 } 2515 2516 try { 2517 if (followLinks(options)) { 2518 provider(path).checkAccess(path); 2519 } else { 2520 // attempt to read attributes without following links 2521 readAttributes(path, BasicFileAttributes.class, 2522 LinkOption.NOFOLLOW_LINKS); 2523 } 2524 // file exists 2525 return true; 2526 } catch (IOException x) { 2527 // does not exist or unable to determine if file exists 2528 return false; 2529 } 2530 2531 } 2532 2533 /** 2534 * Tests whether the file located by this path does not exist. This method 2535 * is intended for cases where it is required to take action when it can be 2536 * confirmed that a file does not exist. 2537 * 2538 * <p> The {@code options} parameter may be used to indicate how symbolic links 2539 * are handled for the case that the file is a symbolic link. By default, 2540 * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS 2541 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2542 * 2543 * <p> Note that this method is not the complement of the {@link #exists 2544 * exists} method. Where it is not possible to determine if a file exists 2545 * or not then both methods return {@code false}. As with the {@code exists} 2546 * method, the result of this method is immediately outdated. If this 2547 * method indicates the file does exist then there is no guarantee that a 2548 * subsequent attempt to create the file will succeed. Care should be taken 2549 * when using this method in security sensitive applications. 2550 * 2551 * @param path 2552 * the path to the file to test 2553 * @param options 2554 * options indicating how symbolic links are handled 2555 * 2556 * @return {@code true} if the file does not exist; {@code false} if the 2557 * file exists or its existence cannot be determined 2558 * 2559 * @throws SecurityException 2560 * In the case of the default provider, the {@link 2561 * SecurityManager#checkRead(String)} is invoked to check 2562 * read access to the file. 2563 */ 2564 public static boolean notExists(Path path, LinkOption... options) { 2565 try { 2566 if (followLinks(options)) { 2567 provider(path).checkAccess(path); 2568 } else { 2569 // attempt to read attributes without following links 2570 readAttributes(path, BasicFileAttributes.class, 2571 LinkOption.NOFOLLOW_LINKS); 2572 } 2573 // file exists 2574 return false; 2575 } catch (NoSuchFileException x) { 2576 // file confirmed not to exist 2577 return true; 2578 } catch (IOException x) { 2579 return false; 2580 } 2581 } 2582 2583 /** 2584 * Used by isReadable, isWritable, isExecutable to test access to a file. 2585 */ 2586 private static boolean isAccessible(Path path, AccessMode... modes) { 2587 try { 2588 provider(path).checkAccess(path, modes); 2589 return true; 2590 } catch (IOException x) { 2591 return false; 2592 } 2593 } 2594 2595 /** 2596 * Tests whether a file is readable. This method checks that a file exists 2597 * and that this Java virtual machine has appropriate privileges that would 2598 * allow it open the file for reading. Depending on the implementation, this 2599 * method may require to read file permissions, access control lists, or 2600 * other file attributes in order to check the effective access to the file. 2601 * Consequently, this method may not be atomic with respect to other file 2602 * system operations. 2603 * 2604 * <p> Note that the result of this method is immediately outdated, there is 2605 * no guarantee that a subsequent attempt to open the file for reading will 2606 * succeed (or even that it will access the same file). Care should be taken 2607 * when using this method in security sensitive applications. 2608 * 2609 * @param path 2610 * the path to the file to check 2611 * 2612 * @return {@code true} if the file exists and is readable; {@code false} 2613 * if the file does not exist, read access would be denied because 2614 * the Java virtual machine has insufficient privileges, or access 2615 * cannot be determined 2616 * 2617 * @throws SecurityException 2618 * In the case of the default provider, and a security manager is 2619 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2620 * is invoked to check read access to the file. 2621 */ 2622 public static boolean isReadable(Path path) { 2623 return isAccessible(path, AccessMode.READ); 2624 } 2625 2626 /** 2627 * Tests whether a file is writable. This method checks that a file exists 2628 * and that this Java virtual machine has appropriate privileges that would 2629 * allow it open the file for writing. Depending on the implementation, this 2630 * method may require to read file permissions, access control lists, or 2631 * other file attributes in order to check the effective access to the file. 2632 * Consequently, this method may not be atomic with respect to other file 2633 * system operations. 2634 * 2635 * <p> Note that result of this method is immediately outdated, there is no 2636 * guarantee that a subsequent attempt to open the file for writing will 2637 * succeed (or even that it will access the same file). Care should be taken 2638 * when using this method in security sensitive applications. 2639 * 2640 * @param path 2641 * the path to the file to check 2642 * 2643 * @return {@code true} if the file exists and is writable; {@code false} 2644 * if the file does not exist, write access would be denied because 2645 * the Java virtual machine has insufficient privileges, or access 2646 * cannot be determined 2647 * 2648 * @throws SecurityException 2649 * In the case of the default provider, and a security manager is 2650 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2651 * is invoked to check write access to the file. 2652 */ 2653 public static boolean isWritable(Path path) { 2654 return isAccessible(path, AccessMode.WRITE); 2655 } 2656 2657 /** 2658 * Tests whether a file is executable. This method checks that a file exists 2659 * and that this Java virtual machine has appropriate privileges to {@link 2660 * Runtime#exec execute} the file. The semantics may differ when checking 2661 * access to a directory. For example, on UNIX systems, checking for 2662 * execute access checks that the Java virtual machine has permission to 2663 * search the directory in order to access file or subdirectories. 2664 * 2665 * <p> Depending on the implementation, this method may require to read file 2666 * permissions, access control lists, or other file attributes in order to 2667 * check the effective access to the file. Consequently, this method may not 2668 * be atomic with respect to other file system operations. 2669 * 2670 * <p> Note that the result of this method is immediately outdated, there is 2671 * no guarantee that a subsequent attempt to execute the file will succeed 2672 * (or even that it will access the same file). Care should be taken when 2673 * using this method in security sensitive applications. 2674 * 2675 * @param path 2676 * the path to the file to check 2677 * 2678 * @return {@code true} if the file exists and is executable; {@code false} 2679 * if the file does not exist, execute access would be denied because 2680 * the Java virtual machine has insufficient privileges, or access 2681 * cannot be determined 2682 * 2683 * @throws SecurityException 2684 * In the case of the default provider, and a security manager is 2685 * installed, the {@link SecurityManager#checkExec(String) 2686 * checkExec} is invoked to check execute access to the file. 2687 */ 2688 public static boolean isExecutable(Path path) { 2689 return isAccessible(path, AccessMode.EXECUTE); 2690 } 2691 2692 // -- Recursive operations -- 2693 2694 /** 2695 * Walks a file tree. 2696 * 2697 * <p> This method walks a file tree rooted at a given starting file. The 2698 * file tree traversal is <em>depth-first</em> with the given {@link 2699 * FileVisitor} invoked for each file encountered. File tree traversal 2700 * completes when all accessible files in the tree have been visited, or a 2701 * visit method returns a result of {@link FileVisitResult#TERMINATE 2702 * TERMINATE}. Where a visit method terminates due an {@code IOException}, 2703 * an uncaught error, or runtime exception, then the traversal is terminated 2704 * and the error or exception is propagated to the caller of this method. 2705 * 2706 * <p> For each file encountered this method attempts to read its {@link 2707 * java.nio.file.attribute.BasicFileAttributes}. If the file is not a 2708 * directory then the {@link FileVisitor#visitFile visitFile} method is 2709 * invoked with the file attributes. If the file attributes cannot be read, 2710 * due to an I/O exception, then the {@link FileVisitor#visitFileFailed 2711 * visitFileFailed} method is invoked with the I/O exception. 2712 * 2713 * <p> Where the file is a directory, and the directory could not be opened, 2714 * then the {@code visitFileFailed} method is invoked with the I/O exception, 2715 * after which, the file tree walk continues, by default, at the next 2716 * <em>sibling</em> of the directory. 2717 * 2718 * <p> Where the directory is opened successfully, then the entries in the 2719 * directory, and their <em>descendants</em> are visited. When all entries 2720 * have been visited, or an I/O error occurs during iteration of the 2721 * directory, then the directory is closed and the visitor's {@link 2722 * FileVisitor#postVisitDirectory postVisitDirectory} method is invoked. 2723 * The file tree walk then continues, by default, at the next <em>sibling</em> 2724 * of the directory. 2725 * 2726 * <p> By default, symbolic links are not automatically followed by this 2727 * method. If the {@code options} parameter contains the {@link 2728 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are 2729 * followed. When following links, and the attributes of the target cannot 2730 * be read, then this method attempts to get the {@code BasicFileAttributes} 2731 * of the link. If they can be read then the {@code visitFile} method is 2732 * invoked with the attributes of the link (otherwise the {@code visitFileFailed} 2733 * method is invoked as specified above). 2734 * 2735 * <p> If the {@code options} parameter contains the {@link 2736 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps 2737 * track of directories visited so that cycles can be detected. A cycle 2738 * arises when there is an entry in a directory that is an ancestor of the 2739 * directory. Cycle detection is done by recording the {@link 2740 * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, 2741 * or if file keys are not available, by invoking the {@link #isSameFile 2742 * isSameFile} method to test if a directory is the same file as an 2743 * ancestor. When a cycle is detected it is treated as an I/O error, and the 2744 * {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with 2745 * an instance of {@link FileSystemLoopException}. 2746 * 2747 * <p> The {@code maxDepth} parameter is the maximum number of levels of 2748 * directories to visit. A value of {@code 0} means that only the starting 2749 * file is visited, unless denied by the security manager. A value of 2750 * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all 2751 * levels should be visited. The {@code visitFile} method is invoked for all 2752 * files, including directories, encountered at {@code maxDepth}, unless the 2753 * basic file attributes cannot be read, in which case the {@code 2754 * visitFileFailed} method is invoked. 2755 * 2756 * <p> If a visitor returns a result of {@code null} then {@code 2757 * NullPointerException} is thrown. 2758 * 2759 * <p> When a security manager is installed and it denies access to a file 2760 * (or directory), then it is ignored and the visitor is not invoked for 2761 * that file (or directory). 2762 * 2763 * @param start 2764 * the starting file 2765 * @param options 2766 * options to configure the traversal 2767 * @param maxDepth 2768 * the maximum number of directory levels to visit 2769 * @param visitor 2770 * the file visitor to invoke for each file 2771 * 2772 * @return the starting file 2773 * 2774 * @throws IllegalArgumentException 2775 * if the {@code maxDepth} parameter is negative 2776 * @throws SecurityException 2777 * If the security manager denies access to the starting file. 2778 * In the case of the default provider, the {@link 2779 * SecurityManager#checkRead(String) checkRead} method is invoked 2780 * to check read access to the directory. 2781 * @throws IOException 2782 * if an I/O error is thrown by a visitor method 2783 */ 2784 public static Path walkFileTree(Path start, 2785 Set<FileVisitOption> options, 2786 int maxDepth, 2787 FileVisitor<? super Path> visitor) 2788 throws IOException 2789 { 2790 /** 2791 * Create a FileTreeWalker to walk the file tree, invoking the visitor 2792 * for each event. 2793 */ 2794 try (FileTreeWalker walker = new FileTreeWalker(options, maxDepth)) { 2795 FileTreeWalker.Event ev = walker.walk(start); 2796 do { 2797 FileVisitResult result; 2798 switch (ev.type()) { 2799 case ENTRY : 2800 IOException ioe = ev.ioeException(); 2801 if (ioe == null) { 2802 assert ev.attributes() != null; 2803 result = visitor.visitFile(ev.file(), ev.attributes()); 2804 } else { 2805 result = visitor.visitFileFailed(ev.file(), ioe); 2806 } 2807 break; 2808 2809 case START_DIRECTORY : 2810 result = visitor.preVisitDirectory(ev.file(), ev.attributes()); 2811 2812 // if SKIP_SIBLINGS and SKIP_SUBTREE is returned then 2813 // there shouldn't be any more events for the current 2814 // directory. 2815 if (result == FileVisitResult.SKIP_SUBTREE || 2816 result == FileVisitResult.SKIP_SIBLINGS) 2817 walker.pop(); 2818 break; 2819 2820 case END_DIRECTORY : 2821 result = visitor.postVisitDirectory(ev.file(), ev.ioeException()); 2822 2823 // SKIP_SIBLINGS is a no-op for postVisitDirectory 2824 if (result == FileVisitResult.SKIP_SIBLINGS) 2825 result = FileVisitResult.CONTINUE; 2826 break; 2827 2828 default : 2829 throw new AssertionError("Should not get here"); 2830 } 2831 2832 if (Objects.requireNonNull(result) != FileVisitResult.CONTINUE) { 2833 if (result == FileVisitResult.TERMINATE) { 2834 break; 2835 } else if (result == FileVisitResult.SKIP_SIBLINGS) { 2836 walker.skipRemainingSiblings(); 2837 } 2838 } 2839 ev = walker.next(); 2840 } while (ev != null); 2841 } 2842 2843 return start; 2844 } 2845 2846 /** 2847 * Walks a file tree. 2848 * 2849 * <p> This method works as if invoking it were equivalent to evaluating the 2850 * expression: 2851 * <blockquote><pre> 2852 * walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor) 2853 * </pre></blockquote> 2854 * In other words, it does not follow symbolic links, and visits all levels 2855 * of the file tree. 2856 * 2857 * @param start 2858 * the starting file 2859 * @param visitor 2860 * the file visitor to invoke for each file 2861 * 2862 * @return the starting file 2863 * 2864 * @throws SecurityException 2865 * If the security manager denies access to the starting file. 2866 * In the case of the default provider, the {@link 2867 * SecurityManager#checkRead(String) checkRead} method is invoked 2868 * to check read access to the directory. 2869 * @throws IOException 2870 * if an I/O error is thrown by a visitor method 2871 */ 2872 public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) 2873 throws IOException 2874 { 2875 return walkFileTree(start, 2876 EnumSet.noneOf(FileVisitOption.class), 2877 Integer.MAX_VALUE, 2878 visitor); 2879 } 2880 2881 2882 // -- Utility methods for simple usages -- 2883 2884 2885 /** 2886 * Opens a file for reading, returning a {@code BufferedReader} that may be 2887 * used to read text from the file in an efficient manner. Bytes from the 2888 * file are decoded into characters using the specified charset. Reading 2889 * commences at the beginning of the file. 2890 * 2891 * <p> The {@code Reader} methods that read from the file throw {@code 2892 * IOException} if a malformed or unmappable byte sequence is read. 2893 * 2894 * @param path 2895 * the path to the file 2896 * @param cs 2897 * the charset to use for decoding 2898 * 2899 * @return a new buffered reader, with default buffer size, to read text 2900 * from the file 2901 * 2902 * @throws IOException 2903 * if an I/O error occurs opening the file 2904 * @throws SecurityException 2905 * In the case of the default provider, and a security manager is 2906 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2907 * method is invoked to check read access to the file. 2908 * 2909 * @see #readAllLines 2910 */ 2911 public static BufferedReader newBufferedReader(Path path, Charset cs) 2912 throws IOException 2913 { 2914 CharsetDecoder decoder = cs.newDecoder(); 2915 Reader reader = new InputStreamReader(newInputStream(path), decoder); 2916 return new BufferedReader(reader); 2917 } 2918 2919 /** 2920 * Opens a file for reading, returning a {@code BufferedReader} to read text 2921 * from the file in an efficient manner. Bytes from the file are decoded into 2922 * characters using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset 2923 * charset}. 2924 * 2925 * <p> This method works as if invoking it were equivalent to evaluating the 2926 * expression: 2927 * <pre>{@code 2928 * Files.newBufferedReader(path, StandardCharsets.UTF_8) 2929 * }</pre> 2930 * 2931 * @param path 2932 * the path to the file 2933 * 2934 * @return a new buffered reader, with default buffer size, to read text 2935 * from the file 2936 * 2937 * @throws IOException 2938 * if an I/O error occurs opening the file 2939 * @throws SecurityException 2940 * In the case of the default provider, and a security manager is 2941 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2942 * method is invoked to check read access to the file. 2943 * 2944 * @since 1.8 2945 */ 2946 public static BufferedReader newBufferedReader(Path path) throws IOException { 2947 return newBufferedReader(path, StandardCharsets.UTF_8); 2948 } 2949 2950 /** 2951 * Opens or creates a file for writing, returning a {@code BufferedWriter} 2952 * that may be used to write text to the file in an efficient manner. 2953 * The {@code options} parameter specifies how the file is created or 2954 * opened. If no options are present then this method works as if the {@link 2955 * StandardOpenOption#CREATE CREATE}, {@link 2956 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 2957 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 2958 * opens the file for writing, creating the file if it doesn't exist, or 2959 * initially truncating an existing {@link #isRegularFile regular-file} to 2960 * a size of {@code 0} if it exists. 2961 * 2962 * <p> The {@code Writer} methods to write text throw {@code IOException} 2963 * if the text cannot be encoded using the specified charset. 2964 * 2965 * @param path 2966 * the path to the file 2967 * @param cs 2968 * the charset to use for encoding 2969 * @param options 2970 * options specifying how the file is opened 2971 * 2972 * @return a new buffered writer, with default buffer size, to write text 2973 * to the file 2974 * 2975 * @throws IllegalArgumentException 2976 * if {@code options} contains an invalid combination of options 2977 * @throws IOException 2978 * if an I/O error occurs opening or creating the file 2979 * @throws UnsupportedOperationException 2980 * if an unsupported option is specified 2981 * @throws SecurityException 2982 * In the case of the default provider, and a security manager is 2983 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2984 * method is invoked to check write access to the file. The {@link 2985 * SecurityManager#checkDelete(String) checkDelete} method is 2986 * invoked to check delete access if the file is opened with the 2987 * {@code DELETE_ON_CLOSE} option. 2988 * 2989 * @see #write(Path,Iterable,Charset,OpenOption[]) 2990 */ 2991 public static BufferedWriter newBufferedWriter(Path path, Charset cs, 2992 OpenOption... options) 2993 throws IOException 2994 { 2995 CharsetEncoder encoder = cs.newEncoder(); 2996 Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder); 2997 return new BufferedWriter(writer); 2998 } 2999 3000 /** 3001 * Opens or creates a file for writing, returning a {@code BufferedWriter} 3002 * to write text to the file in an efficient manner. The text is encoded 3003 * into bytes for writing using the {@link StandardCharsets#UTF_8 UTF-8} 3004 * {@link Charset charset}. 3005 * 3006 * <p> This method works as if invoking it were equivalent to evaluating the 3007 * expression: 3008 * <pre>{@code 3009 * Files.newBufferedWriter(path, StandardCharsets.UTF_8, options) 3010 * }</pre> 3011 * 3012 * @param path 3013 * the path to the file 3014 * @param options 3015 * options specifying how the file is opened 3016 * 3017 * @return a new buffered writer, with default buffer size, to write text 3018 * to the file 3019 * 3020 * @throws IllegalArgumentException 3021 * if {@code options} contains an invalid combination of options 3022 * @throws IOException 3023 * if an I/O error occurs opening or creating the file 3024 * @throws UnsupportedOperationException 3025 * if an unsupported option is specified 3026 * @throws SecurityException 3027 * In the case of the default provider, and a security manager is 3028 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3029 * method is invoked to check write access to the file. The {@link 3030 * SecurityManager#checkDelete(String) checkDelete} method is 3031 * invoked to check delete access if the file is opened with the 3032 * {@code DELETE_ON_CLOSE} option. 3033 * 3034 * @since 1.8 3035 */ 3036 public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) 3037 throws IOException 3038 { 3039 return newBufferedWriter(path, StandardCharsets.UTF_8, options); 3040 } 3041 3042 /** 3043 * Copies all bytes from an input stream to a file. On return, the input 3044 * stream will be at end of stream. 3045 * 3046 * <p> By default, the copy fails if the target file already exists or is a 3047 * symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING 3048 * REPLACE_EXISTING} option is specified, and the target file already exists, 3049 * then it is replaced if it is not a non-empty directory. If the target 3050 * file exists and is a symbolic link, then the symbolic link is replaced. 3051 * In this release, the {@code REPLACE_EXISTING} option is the only option 3052 * required to be supported by this method. Additional options may be 3053 * supported in future releases. 3054 * 3055 * <p> If an I/O error occurs reading from the input stream or writing to 3056 * the file, then it may do so after the target file has been created and 3057 * after some bytes have been read or written. Consequently the input 3058 * stream may not be at end of stream and may be in an inconsistent state. 3059 * It is strongly recommended that the input stream be promptly closed if an 3060 * I/O error occurs. 3061 * 3062 * <p> This method may block indefinitely reading from the input stream (or 3063 * writing to the file). The behavior for the case that the input stream is 3064 * <i>asynchronously closed</i> or the thread interrupted during the copy is 3065 * highly input stream and file system provider specific and therefore not 3066 * specified. 3067 * 3068 * <p> <b>Usage example</b>: Suppose we want to capture a web page and save 3069 * it to a file: 3070 * <pre> 3071 * Path path = ... 3072 * URI u = URI.create("http://www.example.com/"); 3073 * try (InputStream in = u.toURL().openStream()) { 3074 * Files.copy(in, path); 3075 * } 3076 * </pre> 3077 * 3078 * @param in 3079 * the input stream to read from 3080 * @param target 3081 * the path to the file 3082 * @param options 3083 * options specifying how the copy should be done 3084 * 3085 * @return the number of bytes read or written 3086 * 3087 * @throws IOException 3088 * if an I/O error occurs when reading or writing 3089 * @throws FileAlreadyExistsException 3090 * if the target file exists but cannot be replaced because the 3091 * {@code REPLACE_EXISTING} option is not specified <i>(optional 3092 * specific exception)</i> 3093 * @throws DirectoryNotEmptyException 3094 * the {@code REPLACE_EXISTING} option is specified but the file 3095 * cannot be replaced because it is a non-empty directory 3096 * <i>(optional specific exception)</i> * 3097 * @throws UnsupportedOperationException 3098 * if {@code options} contains a copy option that is not supported 3099 * @throws SecurityException 3100 * In the case of the default provider, and a security manager is 3101 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3102 * method is invoked to check write access to the file. Where the 3103 * {@code REPLACE_EXISTING} option is specified, the security 3104 * manager's {@link SecurityManager#checkDelete(String) checkDelete} 3105 * method is invoked to check that an existing file can be deleted. 3106 */ 3107 public static long copy(InputStream in, Path target, CopyOption... options) 3108 throws IOException 3109 { 3110 // ensure not null before opening file 3111 Objects.requireNonNull(in); 3112 3113 // check for REPLACE_EXISTING 3114 boolean replaceExisting = false; 3115 for (CopyOption opt: options) { 3116 if (opt == StandardCopyOption.REPLACE_EXISTING) { 3117 replaceExisting = true; 3118 } else { 3119 if (opt == null) { 3120 throw new NullPointerException("options contains 'null'"); 3121 } else { 3122 throw new UnsupportedOperationException(opt + " not supported"); 3123 } 3124 } 3125 } 3126 3127 // attempt to delete an existing file 3128 SecurityException se = null; 3129 if (replaceExisting) { 3130 try { 3131 deleteIfExists(target); 3132 } catch (SecurityException x) { 3133 se = x; 3134 } 3135 } 3136 3137 // attempt to create target file. If it fails with 3138 // FileAlreadyExistsException then it may be because the security 3139 // manager prevented us from deleting the file, in which case we just 3140 // throw the SecurityException. 3141 OutputStream ostream; 3142 try { 3143 ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW, 3144 StandardOpenOption.WRITE); 3145 } catch (FileAlreadyExistsException x) { 3146 if (se != null) 3147 throw se; 3148 // someone else won the race and created the file 3149 throw x; 3150 } 3151 3152 // do the copy 3153 try (OutputStream out = ostream) { 3154 return in.transferTo(out); 3155 } 3156 } 3157 3158 /** 3159 * Copies all bytes from a file to an output stream. 3160 * 3161 * <p> If an I/O error occurs reading from the file or writing to the output 3162 * stream, then it may do so after some bytes have been read or written. 3163 * Consequently the output stream may be in an inconsistent state. It is 3164 * strongly recommended that the output stream be promptly closed if an I/O 3165 * error occurs. 3166 * 3167 * <p> This method may block indefinitely writing to the output stream (or 3168 * reading from the file). The behavior for the case that the output stream 3169 * is <i>asynchronously closed</i> or the thread interrupted during the copy 3170 * is highly output stream and file system provider specific and therefore 3171 * not specified. 3172 * 3173 * <p> Note that if the given output stream is {@link java.io.Flushable} 3174 * then its {@link java.io.Flushable#flush flush} method may need to invoked 3175 * after this method completes so as to flush any buffered output. 3176 * 3177 * @param source 3178 * the path to the file 3179 * @param out 3180 * the output stream to write to 3181 * 3182 * @return the number of bytes read or written 3183 * 3184 * @throws IOException 3185 * if an I/O error occurs when reading or writing 3186 * @throws SecurityException 3187 * In the case of the default provider, and a security manager is 3188 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3189 * method is invoked to check read access to the file. 3190 */ 3191 public static long copy(Path source, OutputStream out) throws IOException { 3192 // ensure not null before opening file 3193 Objects.requireNonNull(out); 3194 3195 try (InputStream in = newInputStream(source)) { 3196 return in.transferTo(out); 3197 } 3198 } 3199 3200 private static final jdk.internal.access.JavaLangAccess JLA = 3201 jdk.internal.access.SharedSecrets.getJavaLangAccess(); 3202 3203 /** 3204 * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint 3205 * about how many bytes the stream will have. 3206 * 3207 * @param source 3208 * the input stream to read from 3209 * @param initialSize 3210 * the initial size of the byte array to allocate 3211 * 3212 * @return a byte array containing the bytes read from the file 3213 * 3214 * @throws IOException 3215 * if an I/O error occurs reading from the stream 3216 * @throws OutOfMemoryError 3217 * if an array of the required size cannot be allocated 3218 */ 3219 private static byte[] read(InputStream source, int initialSize) throws IOException { 3220 int capacity = initialSize; 3221 byte[] buf = new byte[capacity]; 3222 int nread = 0; 3223 int n; 3224 for (;;) { 3225 // read to EOF which may read more or less than initialSize (eg: file 3226 // is truncated while we are reading) 3227 while ((n = source.read(buf, nread, capacity - nread)) > 0) 3228 nread += n; 3229 3230 // if last call to source.read() returned -1, we are done 3231 // otherwise, try to read one more byte; if that failed we're done too 3232 if (n < 0 || (n = source.read()) < 0) 3233 break; 3234 3235 // one more byte was read; need to allocate a larger buffer 3236 capacity = Math.max(ArraysSupport.newCapacity(capacity, 1, capacity), 3237 BUFFER_SIZE); 3238 buf = Arrays.copyOf(buf, capacity); 3239 buf[nread++] = (byte)n; 3240 } 3241 return (capacity == nread) ? buf : Arrays.copyOf(buf, nread); 3242 } 3243 3244 /** 3245 * Reads all the bytes from a file. The method ensures that the file is 3246 * closed when all bytes have been read or an I/O error, or other runtime 3247 * exception, is thrown. 3248 * 3249 * <p> Note that this method is intended for simple cases where it is 3250 * convenient to read all bytes into a byte array. It is not intended for 3251 * reading in large files. 3252 * 3253 * @param path 3254 * the path to the file 3255 * 3256 * @return a byte array containing the bytes read from the file 3257 * 3258 * @throws IOException 3259 * if an I/O error occurs reading from the stream 3260 * @throws OutOfMemoryError 3261 * if an array of the required size cannot be allocated, for 3262 * example the file is larger that {@code 2GB} 3263 * @throws SecurityException 3264 * In the case of the default provider, and a security manager is 3265 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3266 * method is invoked to check read access to the file. 3267 */ 3268 public static byte[] readAllBytes(Path path) throws IOException { 3269 try (SeekableByteChannel sbc = Files.newByteChannel(path); 3270 InputStream in = Channels.newInputStream(sbc)) { 3271 if (sbc instanceof FileChannelImpl) 3272 ((FileChannelImpl) sbc).setUninterruptible(); 3273 long size = sbc.size(); 3274 if (size > (long) Integer.MAX_VALUE) 3275 throw new OutOfMemoryError("Required array size too large"); 3276 return read(in, (int)size); 3277 } 3278 } 3279 3280 /** 3281 * Reads all content from a file into a string, decoding from bytes to characters 3282 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3283 * The method ensures that the file is closed when all content have been read 3284 * or an I/O error, or other runtime exception, is thrown. 3285 * 3286 * <p> This method is equivalent to: 3287 * {@code readString(path, StandardCharsets.UTF_8) } 3288 * 3289 * @param path the path to the file 3290 * 3291 * @return a String containing the content read from the file 3292 * 3293 * @throws IOException 3294 * if an I/O error occurs reading from the file or a malformed or 3295 * unmappable byte sequence is read 3296 * @throws OutOfMemoryError 3297 * if the file is extremely large, for example larger than {@code 2GB} 3298 * @throws SecurityException 3299 * In the case of the default provider, and a security manager is 3300 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3301 * method is invoked to check read access to the file. 3302 * 3303 * @since 11 3304 */ 3305 public static String readString(Path path) throws IOException { 3306 return readString(path, StandardCharsets.UTF_8); 3307 } 3308 3309 /** 3310 * Reads all characters from a file into a string, decoding from bytes to characters 3311 * using the specified {@linkplain Charset charset}. 3312 * The method ensures that the file is closed when all content have been read 3313 * or an I/O error, or other runtime exception, is thrown. 3314 * 3315 * <p> This method reads all content including the line separators in the middle 3316 * and/or at the end. The resulting string will contain line separators as they 3317 * appear in the file. 3318 * 3319 * @apiNote 3320 * This method is intended for simple cases where it is appropriate and convenient 3321 * to read the content of a file into a String. It is not intended for reading 3322 * very large files. 3323 * 3324 * 3325 * 3326 * @param path the path to the file 3327 * @param cs the charset to use for decoding 3328 * 3329 * @return a String containing the content read from the file 3330 * 3331 * @throws IOException 3332 * if an I/O error occurs reading from the file or a malformed or 3333 * unmappable byte sequence is read 3334 * @throws OutOfMemoryError 3335 * if the file is extremely large, for example larger than {@code 2GB} 3336 * @throws SecurityException 3337 * In the case of the default provider, and a security manager is 3338 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3339 * method is invoked to check read access to the file. 3340 * 3341 * @since 11 3342 */ 3343 public static String readString(Path path, Charset cs) throws IOException { 3344 Objects.requireNonNull(path); 3345 Objects.requireNonNull(cs); 3346 3347 byte[] ba = readAllBytes(path); 3348 return JLA.newStringNoRepl(ba, cs); 3349 } 3350 3351 /** 3352 * Read all lines from a file. This method ensures that the file is 3353 * closed when all bytes have been read or an I/O error, or other runtime 3354 * exception, is thrown. Bytes from the file are decoded into characters 3355 * using the specified charset. 3356 * 3357 * <p> This method recognizes the following as line terminators: 3358 * <ul> 3359 * <li> <code>\u000D</code> followed by <code>\u000A</code>, 3360 * CARRIAGE RETURN followed by LINE FEED </li> 3361 * <li> <code>\u000A</code>, LINE FEED </li> 3362 * <li> <code>\u000D</code>, CARRIAGE RETURN </li> 3363 * </ul> 3364 * <p> Additional Unicode line terminators may be recognized in future 3365 * releases. 3366 * 3367 * <p> Note that this method is intended for simple cases where it is 3368 * convenient to read all lines in a single operation. It is not intended 3369 * for reading in large files. 3370 * 3371 * @param path 3372 * the path to the file 3373 * @param cs 3374 * the charset to use for decoding 3375 * 3376 * @return the lines from the file as a {@code List}; whether the {@code 3377 * List} is modifiable or not is implementation dependent and 3378 * therefore not specified 3379 * 3380 * @throws IOException 3381 * if an I/O error occurs reading from the file or a malformed or 3382 * unmappable byte sequence is read 3383 * @throws SecurityException 3384 * In the case of the default provider, and a security manager is 3385 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3386 * method is invoked to check read access to the file. 3387 * 3388 * @see #newBufferedReader 3389 */ 3390 public static List<String> readAllLines(Path path, Charset cs) throws IOException { 3391 try (BufferedReader reader = newBufferedReader(path, cs)) { 3392 List<String> result = new ArrayList<>(); 3393 for (;;) { 3394 String line = reader.readLine(); 3395 if (line == null) 3396 break; 3397 result.add(line); 3398 } 3399 return result; 3400 } 3401 } 3402 3403 /** 3404 * Read all lines from a file. Bytes from the file are decoded into characters 3405 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3406 * 3407 * <p> This method works as if invoking it were equivalent to evaluating the 3408 * expression: 3409 * <pre>{@code 3410 * Files.readAllLines(path, StandardCharsets.UTF_8) 3411 * }</pre> 3412 * 3413 * @param path 3414 * the path to the file 3415 * 3416 * @return the lines from the file as a {@code List}; whether the {@code 3417 * List} is modifiable or not is implementation dependent and 3418 * therefore not specified 3419 * 3420 * @throws IOException 3421 * if an I/O error occurs reading from the file or a malformed or 3422 * unmappable byte sequence is read 3423 * @throws SecurityException 3424 * In the case of the default provider, and a security manager is 3425 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3426 * method is invoked to check read access to the file. 3427 * 3428 * @since 1.8 3429 */ 3430 public static List<String> readAllLines(Path path) throws IOException { 3431 return readAllLines(path, StandardCharsets.UTF_8); 3432 } 3433 3434 /** 3435 * Writes bytes to a file. The {@code options} parameter specifies how 3436 * the file is created or opened. If no options are present then this method 3437 * works as if the {@link StandardOpenOption#CREATE CREATE}, {@link 3438 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3439 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3440 * opens the file for writing, creating the file if it doesn't exist, or 3441 * initially truncating an existing {@link #isRegularFile regular-file} to 3442 * a size of {@code 0}. All bytes in the byte array are written to the file. 3443 * The method ensures that the file is closed when all bytes have been 3444 * written (or an I/O error or other runtime exception is thrown). If an I/O 3445 * error occurs then it may do so after the file has been created or 3446 * truncated, or after some bytes have been written to the file. 3447 * 3448 * <p> <b>Usage example</b>: By default the method creates a new file or 3449 * overwrites an existing file. Suppose you instead want to append bytes 3450 * to an existing file: 3451 * <pre> 3452 * Path path = ... 3453 * byte[] bytes = ... 3454 * Files.write(path, bytes, StandardOpenOption.APPEND); 3455 * </pre> 3456 * 3457 * @param path 3458 * the path to the file 3459 * @param bytes 3460 * the byte array with the bytes to write 3461 * @param options 3462 * options specifying how the file is opened 3463 * 3464 * @return the path 3465 * 3466 * @throws IllegalArgumentException 3467 * if {@code options} contains an invalid combination of options 3468 * @throws IOException 3469 * if an I/O error occurs writing to or creating the file 3470 * @throws UnsupportedOperationException 3471 * if an unsupported option is specified 3472 * @throws SecurityException 3473 * In the case of the default provider, and a security manager is 3474 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3475 * method is invoked to check write access to the file. The {@link 3476 * SecurityManager#checkDelete(String) checkDelete} method is 3477 * invoked to check delete access if the file is opened with the 3478 * {@code DELETE_ON_CLOSE} option. 3479 */ 3480 public static Path write(Path path, byte[] bytes, OpenOption... options) 3481 throws IOException 3482 { 3483 // ensure bytes is not null before opening file 3484 Objects.requireNonNull(bytes); 3485 3486 try (OutputStream out = Files.newOutputStream(path, options)) { 3487 int len = bytes.length; 3488 int rem = len; 3489 while (rem > 0) { 3490 int n = Math.min(rem, BUFFER_SIZE); 3491 out.write(bytes, (len-rem), n); 3492 rem -= n; 3493 } 3494 } 3495 return path; 3496 } 3497 3498 /** 3499 * Write lines of text to a file. Each line is a char sequence and is 3500 * written to the file in sequence with each line terminated by the 3501 * platform's line separator, as defined by the system property {@code 3502 * line.separator}. Characters are encoded into bytes using the specified 3503 * charset. 3504 * 3505 * <p> The {@code options} parameter specifies how the file is created 3506 * or opened. If no options are present then this method works as if the 3507 * {@link StandardOpenOption#CREATE CREATE}, {@link 3508 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3509 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3510 * opens the file for writing, creating the file if it doesn't exist, or 3511 * initially truncating an existing {@link #isRegularFile regular-file} to 3512 * a size of {@code 0}. The method ensures that the file is closed when all 3513 * lines have been written (or an I/O error or other runtime exception is 3514 * thrown). If an I/O error occurs then it may do so after the file has 3515 * been created or truncated, or after some bytes have been written to the 3516 * file. 3517 * 3518 * @param path 3519 * the path to the file 3520 * @param lines 3521 * an object to iterate over the char sequences 3522 * @param cs 3523 * the charset to use for encoding 3524 * @param options 3525 * options specifying how the file is opened 3526 * 3527 * @return the path 3528 * 3529 * @throws IllegalArgumentException 3530 * if {@code options} contains an invalid combination of options 3531 * @throws IOException 3532 * if an I/O error occurs writing to or creating the file, or the 3533 * text cannot be encoded using the specified charset 3534 * @throws UnsupportedOperationException 3535 * if an unsupported option is specified 3536 * @throws SecurityException 3537 * In the case of the default provider, and a security manager is 3538 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3539 * method is invoked to check write access to the file. The {@link 3540 * SecurityManager#checkDelete(String) checkDelete} method is 3541 * invoked to check delete access if the file is opened with the 3542 * {@code DELETE_ON_CLOSE} option. 3543 */ 3544 public static Path write(Path path, Iterable<? extends CharSequence> lines, 3545 Charset cs, OpenOption... options) 3546 throws IOException 3547 { 3548 // ensure lines is not null before opening file 3549 Objects.requireNonNull(lines); 3550 CharsetEncoder encoder = cs.newEncoder(); 3551 OutputStream out = newOutputStream(path, options); 3552 try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) { 3553 for (CharSequence line: lines) { 3554 writer.append(line); 3555 writer.newLine(); 3556 } 3557 } 3558 return path; 3559 } 3560 3561 /** 3562 * Write lines of text to a file. Characters are encoded into bytes using 3563 * the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3564 * 3565 * <p> This method works as if invoking it were equivalent to evaluating the 3566 * expression: 3567 * <pre>{@code 3568 * Files.write(path, lines, StandardCharsets.UTF_8, options); 3569 * }</pre> 3570 * 3571 * @param path 3572 * the path to the file 3573 * @param lines 3574 * an object to iterate over the char sequences 3575 * @param options 3576 * options specifying how the file is opened 3577 * 3578 * @return the path 3579 * 3580 * @throws IllegalArgumentException 3581 * if {@code options} contains an invalid combination of options 3582 * @throws IOException 3583 * if an I/O error occurs writing to or creating the file, or the 3584 * text cannot be encoded as {@code UTF-8} 3585 * @throws UnsupportedOperationException 3586 * if an unsupported option is specified 3587 * @throws SecurityException 3588 * In the case of the default provider, and a security manager is 3589 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3590 * method is invoked to check write access to the file. The {@link 3591 * SecurityManager#checkDelete(String) checkDelete} method is 3592 * invoked to check delete access if the file is opened with the 3593 * {@code DELETE_ON_CLOSE} option. 3594 * 3595 * @since 1.8 3596 */ 3597 public static Path write(Path path, 3598 Iterable<? extends CharSequence> lines, 3599 OpenOption... options) 3600 throws IOException 3601 { 3602 return write(path, lines, StandardCharsets.UTF_8, options); 3603 } 3604 3605 /** 3606 * Write a {@linkplain java.lang.CharSequence CharSequence} to a file. 3607 * Characters are encoded into bytes using the 3608 * {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3609 * 3610 * <p> This method is equivalent to: 3611 * {@code writeString(path, test, StandardCharsets.UTF_8, options) } 3612 * 3613 * @param path 3614 * the path to the file 3615 * @param csq 3616 * the CharSequence to be written 3617 * @param options 3618 * options specifying how the file is opened 3619 * 3620 * @return the path 3621 * 3622 * @throws IllegalArgumentException 3623 * if {@code options} contains an invalid combination of options 3624 * @throws IOException 3625 * if an I/O error occurs writing to or creating the file, or the 3626 * text cannot be encoded using the specified charset 3627 * @throws UnsupportedOperationException 3628 * if an unsupported option is specified 3629 * @throws SecurityException 3630 * In the case of the default provider, and a security manager is 3631 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3632 * method is invoked to check write access to the file. The {@link 3633 * SecurityManager#checkDelete(String) checkDelete} method is 3634 * invoked to check delete access if the file is opened with the 3635 * {@code DELETE_ON_CLOSE} option. 3636 * 3637 * @since 11 3638 */ 3639 public static Path writeString(Path path, CharSequence csq, OpenOption... options) 3640 throws IOException 3641 { 3642 return writeString(path, csq, StandardCharsets.UTF_8, options); 3643 } 3644 3645 /** 3646 * Write a {@linkplain java.lang.CharSequence CharSequence} to a file. 3647 * Characters are encoded into bytes using the specified 3648 * {@linkplain java.nio.charset.Charset charset}. 3649 * 3650 * <p> All characters are written as they are, including the line separators in 3651 * the char sequence. No extra characters are added. 3652 * 3653 * <p> The {@code options} parameter specifies how the file is created 3654 * or opened. If no options are present then this method works as if the 3655 * {@link StandardOpenOption#CREATE CREATE}, {@link 3656 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3657 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3658 * opens the file for writing, creating the file if it doesn't exist, or 3659 * initially truncating an existing {@link #isRegularFile regular-file} to 3660 * a size of {@code 0}. 3661 * 3662 * 3663 * @param path 3664 * the path to the file 3665 * @param csq 3666 * the CharSequence to be written 3667 * @param cs 3668 * the charset to use for encoding 3669 * @param options 3670 * options specifying how the file is opened 3671 * 3672 * @return the path 3673 * 3674 * @throws IllegalArgumentException 3675 * if {@code options} contains an invalid combination of options 3676 * @throws IOException 3677 * if an I/O error occurs writing to or creating the file, or the 3678 * text cannot be encoded using the specified charset 3679 * @throws UnsupportedOperationException 3680 * if an unsupported option is specified 3681 * @throws SecurityException 3682 * In the case of the default provider, and a security manager is 3683 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3684 * method is invoked to check write access to the file. The {@link 3685 * SecurityManager#checkDelete(String) checkDelete} method is 3686 * invoked to check delete access if the file is opened with the 3687 * {@code DELETE_ON_CLOSE} option. 3688 * 3689 * @since 11 3690 */ 3691 public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) 3692 throws IOException 3693 { 3694 // ensure the text is not null before opening file 3695 Objects.requireNonNull(path); 3696 Objects.requireNonNull(csq); 3697 Objects.requireNonNull(cs); 3698 3699 byte[] bytes = JLA.getBytesNoRepl(String.valueOf(csq), cs); 3700 write(path, bytes, options); 3701 3702 return path; 3703 } 3704 3705 // -- Stream APIs -- 3706 3707 /** 3708 * Return a lazily populated {@code Stream}, the elements of 3709 * which are the entries in the directory. The listing is not recursive. 3710 * 3711 * <p> The elements of the stream are {@link Path} objects that are 3712 * obtained as if by {@link Path#resolve(Path) resolving} the name of the 3713 * directory entry against {@code dir}. Some file systems maintain special 3714 * links to the directory itself and the directory's parent directory. 3715 * Entries representing these links are not included. 3716 * 3717 * <p> The stream is <i>weakly consistent</i>. It is thread safe but does 3718 * not freeze the directory while iterating, so it may (or may not) 3719 * reflect updates to the directory that occur after returning from this 3720 * method. 3721 * 3722 * <p> The returned stream contains a reference to an open directory. 3723 * The directory is closed by closing the stream. 3724 * 3725 * <p> Operating on a closed stream behaves as if the end of stream 3726 * has been reached. Due to read-ahead, one or more elements may be 3727 * returned after the stream has been closed. 3728 * 3729 * <p> If an {@link IOException} is thrown when accessing the directory 3730 * after this method has returned, it is wrapped in an {@link 3731 * UncheckedIOException} which will be thrown from the method that caused 3732 * the access to take place. 3733 * 3734 * @apiNote 3735 * This method must be used within a try-with-resources statement or similar 3736 * control structure to ensure that the stream's open directory is closed 3737 * promptly after the stream's operations have completed. 3738 * 3739 * @param dir The path to the directory 3740 * 3741 * @return The {@code Stream} describing the content of the 3742 * directory 3743 * 3744 * @throws NotDirectoryException 3745 * if the file could not otherwise be opened because it is not 3746 * a directory <i>(optional specific exception)</i> 3747 * @throws IOException 3748 * if an I/O error occurs when opening the directory 3749 * @throws SecurityException 3750 * In the case of the default provider, and a security manager is 3751 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3752 * method is invoked to check read access to the directory. 3753 * 3754 * @see #newDirectoryStream(Path) 3755 * @since 1.8 3756 */ 3757 public static Stream<Path> list(Path dir) throws IOException { 3758 DirectoryStream<Path> ds = Files.newDirectoryStream(dir); 3759 try { 3760 final Iterator<Path> delegate = ds.iterator(); 3761 3762 // Re-wrap DirectoryIteratorException to UncheckedIOException 3763 Iterator<Path> iterator = new Iterator<>() { 3764 @Override 3765 public boolean hasNext() { 3766 try { 3767 return delegate.hasNext(); 3768 } catch (DirectoryIteratorException e) { 3769 throw new UncheckedIOException(e.getCause()); 3770 } 3771 } 3772 @Override 3773 public Path next() { 3774 try { 3775 return delegate.next(); 3776 } catch (DirectoryIteratorException e) { 3777 throw new UncheckedIOException(e.getCause()); 3778 } 3779 } 3780 }; 3781 3782 Spliterator<Path> spliterator = 3783 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT); 3784 return StreamSupport.stream(spliterator, false) 3785 .onClose(asUncheckedRunnable(ds)); 3786 } catch (Error|RuntimeException e) { 3787 try { 3788 ds.close(); 3789 } catch (IOException ex) { 3790 try { 3791 e.addSuppressed(ex); 3792 } catch (Throwable ignore) {} 3793 } 3794 throw e; 3795 } 3796 } 3797 3798 /** 3799 * Return a {@code Stream} that is lazily populated with {@code 3800 * Path} by walking the file tree rooted at a given starting file. The 3801 * file tree is traversed <em>depth-first</em>, the elements in the stream 3802 * are {@link Path} objects that are obtained as if by {@link 3803 * Path#resolve(Path) resolving} the relative path against {@code start}. 3804 * 3805 * <p> The {@code stream} walks the file tree as elements are consumed. 3806 * The {@code Stream} returned is guaranteed to have at least one 3807 * element, the starting file itself. For each file visited, the stream 3808 * attempts to read its {@link BasicFileAttributes}. If the file is a 3809 * directory and can be opened successfully, entries in the directory, and 3810 * their <em>descendants</em> will follow the directory in the stream as 3811 * they are encountered. When all entries have been visited, then the 3812 * directory is closed. The file tree walk then continues at the next 3813 * <em>sibling</em> of the directory. 3814 * 3815 * <p> The stream is <i>weakly consistent</i>. It does not freeze the 3816 * file tree while iterating, so it may (or may not) reflect updates to 3817 * the file tree that occur after returned from this method. 3818 * 3819 * <p> By default, symbolic links are not automatically followed by this 3820 * method. If the {@code options} parameter contains the {@link 3821 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are 3822 * followed. When following links, and the attributes of the target cannot 3823 * be read, then this method attempts to get the {@code BasicFileAttributes} 3824 * of the link. 3825 * 3826 * <p> If the {@code options} parameter contains the {@link 3827 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then the stream keeps 3828 * track of directories visited so that cycles can be detected. A cycle 3829 * arises when there is an entry in a directory that is an ancestor of the 3830 * directory. Cycle detection is done by recording the {@link 3831 * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, 3832 * or if file keys are not available, by invoking the {@link #isSameFile 3833 * isSameFile} method to test if a directory is the same file as an 3834 * ancestor. When a cycle is detected it is treated as an I/O error with 3835 * an instance of {@link FileSystemLoopException}. 3836 * 3837 * <p> The {@code maxDepth} parameter is the maximum number of levels of 3838 * directories to visit. A value of {@code 0} means that only the starting 3839 * file is visited, unless denied by the security manager. A value of 3840 * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all 3841 * levels should be visited. 3842 * 3843 * <p> When a security manager is installed and it denies access to a file 3844 * (or directory), then it is ignored and not included in the stream. 3845 * 3846 * <p> The returned stream contains references to one or more open directories. 3847 * The directories are closed by closing the stream. 3848 * 3849 * <p> If an {@link IOException} is thrown when accessing the directory 3850 * after this method has returned, it is wrapped in an {@link 3851 * UncheckedIOException} which will be thrown from the method that caused 3852 * the access to take place. 3853 * 3854 * @apiNote 3855 * This method must be used within a try-with-resources statement or similar 3856 * control structure to ensure that the stream's open directories are closed 3857 * promptly after the stream's operations have completed. 3858 * 3859 * @param start 3860 * the starting file 3861 * @param maxDepth 3862 * the maximum number of directory levels to visit 3863 * @param options 3864 * options to configure the traversal 3865 * 3866 * @return the {@link Stream} of {@link Path} 3867 * 3868 * @throws IllegalArgumentException 3869 * if the {@code maxDepth} parameter is negative 3870 * @throws SecurityException 3871 * If the security manager denies access to the starting file. 3872 * In the case of the default provider, the {@link 3873 * SecurityManager#checkRead(String) checkRead} method is invoked 3874 * to check read access to the directory. 3875 * @throws IOException 3876 * if an I/O error is thrown when accessing the starting file. 3877 * @since 1.8 3878 */ 3879 public static Stream<Path> walk(Path start, 3880 int maxDepth, 3881 FileVisitOption... options) 3882 throws IOException 3883 { 3884 FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); 3885 try { 3886 Spliterator<FileTreeWalker.Event> spliterator = 3887 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT); 3888 return StreamSupport.stream(spliterator, false) 3889 .onClose(iterator::close) 3890 .map(entry -> entry.file()); 3891 } catch (Error|RuntimeException e) { 3892 iterator.close(); 3893 throw e; 3894 } 3895 } 3896 3897 /** 3898 * Return a {@code Stream} that is lazily populated with {@code 3899 * Path} by walking the file tree rooted at a given starting file. The 3900 * file tree is traversed <em>depth-first</em>, the elements in the stream 3901 * are {@link Path} objects that are obtained as if by {@link 3902 * Path#resolve(Path) resolving} the relative path against {@code start}. 3903 * 3904 * <p> This method works as if invoking it were equivalent to evaluating the 3905 * expression: 3906 * <blockquote><pre> 3907 * walk(start, Integer.MAX_VALUE, options) 3908 * </pre></blockquote> 3909 * In other words, it visits all levels of the file tree. 3910 * 3911 * <p> The returned stream contains references to one or more open directories. 3912 * The directories are closed by closing the stream. 3913 * 3914 * @apiNote 3915 * This method must be used within a try-with-resources statement or similar 3916 * control structure to ensure that the stream's open directories are closed 3917 * promptly after the stream's operations have completed. 3918 * 3919 * @param start 3920 * the starting file 3921 * @param options 3922 * options to configure the traversal 3923 * 3924 * @return the {@link Stream} of {@link Path} 3925 * 3926 * @throws SecurityException 3927 * If the security manager denies access to the starting file. 3928 * In the case of the default provider, the {@link 3929 * SecurityManager#checkRead(String) checkRead} method is invoked 3930 * to check read access to the directory. 3931 * @throws IOException 3932 * if an I/O error is thrown when accessing the starting file. 3933 * 3934 * @see #walk(Path, int, FileVisitOption...) 3935 * @since 1.8 3936 */ 3937 public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException { 3938 return walk(start, Integer.MAX_VALUE, options); 3939 } 3940 3941 /** 3942 * Return a {@code Stream} that is lazily populated with {@code 3943 * Path} by searching for files in a file tree rooted at a given starting 3944 * file. 3945 * 3946 * <p> This method walks the file tree in exactly the manner specified by 3947 * the {@link #walk walk} method. For each file encountered, the given 3948 * {@link BiPredicate} is invoked with its {@link Path} and {@link 3949 * BasicFileAttributes}. The {@code Path} object is obtained as if by 3950 * {@link Path#resolve(Path) resolving} the relative path against {@code 3951 * start} and is only included in the returned {@link Stream} if 3952 * the {@code BiPredicate} returns true. Compare to calling {@link 3953 * java.util.stream.Stream#filter filter} on the {@code Stream} 3954 * returned by {@code walk} method, this method may be more efficient by 3955 * avoiding redundant retrieval of the {@code BasicFileAttributes}. 3956 * 3957 * <p> The returned stream contains references to one or more open directories. 3958 * The directories are closed by closing the stream. 3959 * 3960 * <p> If an {@link IOException} is thrown when accessing the directory 3961 * after returned from this method, it is wrapped in an {@link 3962 * UncheckedIOException} which will be thrown from the method that caused 3963 * the access to take place. 3964 * 3965 * @apiNote 3966 * This method must be used within a try-with-resources statement or similar 3967 * control structure to ensure that the stream's open directories are closed 3968 * promptly after the stream's operations have completed. 3969 * 3970 * @param start 3971 * the starting file 3972 * @param maxDepth 3973 * the maximum number of directory levels to search 3974 * @param matcher 3975 * the function used to decide whether a file should be included 3976 * in the returned stream 3977 * @param options 3978 * options to configure the traversal 3979 * 3980 * @return the {@link Stream} of {@link Path} 3981 * 3982 * @throws IllegalArgumentException 3983 * if the {@code maxDepth} parameter is negative 3984 * @throws SecurityException 3985 * If the security manager denies access to the starting file. 3986 * In the case of the default provider, the {@link 3987 * SecurityManager#checkRead(String) checkRead} method is invoked 3988 * to check read access to the directory. 3989 * @throws IOException 3990 * if an I/O error is thrown when accessing the starting file. 3991 * 3992 * @see #walk(Path, int, FileVisitOption...) 3993 * @since 1.8 3994 */ 3995 public static Stream<Path> find(Path start, 3996 int maxDepth, 3997 BiPredicate<Path, BasicFileAttributes> matcher, 3998 FileVisitOption... options) 3999 throws IOException 4000 { 4001 FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); 4002 try { 4003 Spliterator<FileTreeWalker.Event> spliterator = 4004 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT); 4005 return StreamSupport.stream(spliterator, false) 4006 .onClose(iterator::close) 4007 .filter(entry -> matcher.test(entry.file(), entry.attributes())) 4008 .map(entry -> entry.file()); 4009 } catch (Error|RuntimeException e) { 4010 iterator.close(); 4011 throw e; 4012 } 4013 } 4014 4015 4016 /** 4017 * Read all lines from a file as a {@code Stream}. Unlike {@link 4018 * #readAllLines(Path, Charset) readAllLines}, this method does not read 4019 * all lines into a {@code List}, but instead populates lazily as the stream 4020 * is consumed. 4021 * 4022 * <p> Bytes from the file are decoded into characters using the specified 4023 * charset and the same line terminators as specified by {@code 4024 * readAllLines} are supported. 4025 * 4026 * <p> The returned stream contains a reference to an open file. The file 4027 * is closed by closing the stream. 4028 * 4029 * <p> The file contents should not be modified during the execution of the 4030 * terminal stream operation. Otherwise, the result of the terminal stream 4031 * operation is undefined. 4032 * 4033 * <p> After this method returns, then any subsequent I/O exception that 4034 * occurs while reading from the file or when a malformed or unmappable byte 4035 * sequence is read, is wrapped in an {@link UncheckedIOException} that will 4036 * be thrown from the 4037 * {@link java.util.stream.Stream} method that caused the read to take 4038 * place. In case an {@code IOException} is thrown when closing the file, 4039 * it is also wrapped as an {@code UncheckedIOException}. 4040 * 4041 * @apiNote 4042 * This method must be used within a try-with-resources statement or similar 4043 * control structure to ensure that the stream's open file is closed promptly 4044 * after the stream's operations have completed. 4045 * 4046 * @implNote 4047 * This implementation supports good parallel stream performance for the 4048 * standard charsets {@link StandardCharsets#UTF_8 UTF-8}, 4049 * {@link StandardCharsets#US_ASCII US-ASCII} and 4050 * {@link StandardCharsets#ISO_8859_1 ISO-8859-1}. Such 4051 * <em>line-optimal</em> charsets have the property that the encoded bytes 4052 * of a line feed ('\n') or a carriage return ('\r') are efficiently 4053 * identifiable from other encoded characters when randomly accessing the 4054 * bytes of the file. 4055 * 4056 * <p> For non-<em>line-optimal</em> charsets the stream source's 4057 * spliterator has poor splitting properties, similar to that of a 4058 * spliterator associated with an iterator or that associated with a stream 4059 * returned from {@link BufferedReader#lines()}. Poor splitting properties 4060 * can result in poor parallel stream performance. 4061 * 4062 * <p> For <em>line-optimal</em> charsets the stream source's spliterator 4063 * has good splitting properties, assuming the file contains a regular 4064 * sequence of lines. Good splitting properties can result in good parallel 4065 * stream performance. The spliterator for a <em>line-optimal</em> charset 4066 * takes advantage of the charset properties (a line feed or a carriage 4067 * return being efficient identifiable) such that when splitting it can 4068 * approximately divide the number of covered lines in half. 4069 * 4070 * @param path 4071 * the path to the file 4072 * @param cs 4073 * the charset to use for decoding 4074 * 4075 * @return the lines from the file as a {@code Stream} 4076 * 4077 * @throws IOException 4078 * if an I/O error occurs opening the file 4079 * @throws SecurityException 4080 * In the case of the default provider, and a security manager is 4081 * installed, the {@link SecurityManager#checkRead(String) checkRead} 4082 * method is invoked to check read access to the file. 4083 * 4084 * @see #readAllLines(Path, Charset) 4085 * @see #newBufferedReader(Path, Charset) 4086 * @see java.io.BufferedReader#lines() 4087 * @since 1.8 4088 */ 4089 public static Stream<String> lines(Path path, Charset cs) throws IOException { 4090 // Use the good splitting spliterator if: 4091 // 1) the path is associated with the default file system; 4092 // 2) the character set is supported; and 4093 // 3) the file size is such that all bytes can be indexed by int values 4094 // (this limitation is imposed by ByteBuffer) 4095 if (path.getFileSystem() == FileSystems.getDefault() && 4096 FileChannelLinesSpliterator.SUPPORTED_CHARSET_NAMES.contains(cs.name())) { 4097 FileChannel fc = FileChannel.open(path, StandardOpenOption.READ); 4098 4099 Stream<String> fcls = createFileChannelLinesStream(fc, cs); 4100 if (fcls != null) { 4101 return fcls; 4102 } 4103 fc.close(); 4104 } 4105 4106 return createBufferedReaderLinesStream(Files.newBufferedReader(path, cs)); 4107 } 4108 4109 private static Stream<String> createFileChannelLinesStream(FileChannel fc, Charset cs) throws IOException { 4110 try { 4111 // Obtaining the size from the FileChannel is much faster 4112 // than obtaining using path.toFile().length() 4113 long length = fc.size(); 4114 // FileChannel.size() may in certain circumstances return zero 4115 // for a non-zero length file so disallow this case. 4116 if (length > 0 && length <= Integer.MAX_VALUE) { 4117 Spliterator<String> s = new FileChannelLinesSpliterator(fc, cs, 0, (int) length); 4118 return StreamSupport.stream(s, false) 4119 .onClose(Files.asUncheckedRunnable(fc)); 4120 } 4121 } catch (Error|RuntimeException|IOException e) { 4122 try { 4123 fc.close(); 4124 } catch (IOException ex) { 4125 try { 4126 e.addSuppressed(ex); 4127 } catch (Throwable ignore) { 4128 } 4129 } 4130 throw e; 4131 } 4132 return null; 4133 } 4134 4135 private static Stream<String> createBufferedReaderLinesStream(BufferedReader br) { 4136 try { 4137 return br.lines().onClose(asUncheckedRunnable(br)); 4138 } catch (Error|RuntimeException e) { 4139 try { 4140 br.close(); 4141 } catch (IOException ex) { 4142 try { 4143 e.addSuppressed(ex); 4144 } catch (Throwable ignore) { 4145 } 4146 } 4147 throw e; 4148 } 4149 } 4150 4151 /** 4152 * Read all lines from a file as a {@code Stream}. Bytes from the file are 4153 * decoded into characters using the {@link StandardCharsets#UTF_8 UTF-8} 4154 * {@link Charset charset}. 4155 * 4156 * <p> The returned stream contains a reference to an open file. The file 4157 * is closed by closing the stream. 4158 * 4159 * <p> The file contents should not be modified during the execution of the 4160 * terminal stream operation. Otherwise, the result of the terminal stream 4161 * operation is undefined. 4162 * 4163 * <p> This method works as if invoking it were equivalent to evaluating the 4164 * expression: 4165 * <pre>{@code 4166 * Files.lines(path, StandardCharsets.UTF_8) 4167 * }</pre> 4168 * 4169 * @apiNote 4170 * This method must be used within a try-with-resources statement or similar 4171 * control structure to ensure that the stream's open file is closed promptly 4172 * after the stream's operations have completed. 4173 * 4174 * @param path 4175 * the path to the file 4176 * 4177 * @return the lines from the file as a {@code Stream} 4178 * 4179 * @throws IOException 4180 * if an I/O error occurs opening the file 4181 * @throws SecurityException 4182 * In the case of the default provider, and a security manager is 4183 * installed, the {@link SecurityManager#checkRead(String) checkRead} 4184 * method is invoked to check read access to the file. 4185 * 4186 * @since 1.8 4187 */ 4188 public static Stream<String> lines(Path path) throws IOException { 4189 return lines(path, StandardCharsets.UTF_8); 4190 } 4191 }