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