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