1 /* 2 * Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.nio.file; 27 28 import java.io.BufferedReader; 29 import java.io.BufferedWriter; 30 import java.io.Closeable; 31 import java.io.File; 32 import java.io.IOException; 33 import java.io.InputStream; 34 import java.io.InputStreamReader; 35 import java.io.OutputStream; 36 import java.io.OutputStreamWriter; 37 import java.io.Reader; 38 import java.io.UncheckedIOException; 39 import java.io.Writer; 40 import java.nio.channels.Channels; 41 import java.nio.channels.FileChannel; 42 import java.nio.channels.SeekableByteChannel; 43 import java.nio.charset.Charset; 44 import java.nio.charset.CharsetDecoder; 45 import java.nio.charset.CharsetEncoder; 46 import java.nio.charset.StandardCharsets; 47 import java.nio.file.attribute.BasicFileAttributeView; 48 import java.nio.file.attribute.BasicFileAttributes; 49 import java.nio.file.attribute.DosFileAttributes; // javadoc 50 import java.nio.file.attribute.FileAttribute; 51 import java.nio.file.attribute.FileAttributeView; 52 import java.nio.file.attribute.FileOwnerAttributeView; 53 import java.nio.file.attribute.FileStoreAttributeView; 54 import java.nio.file.attribute.FileTime; 55 import java.nio.file.attribute.PosixFileAttributeView; 56 import java.nio.file.attribute.PosixFileAttributes; 57 import java.nio.file.attribute.PosixFilePermission; 58 import java.nio.file.attribute.UserPrincipal; 59 import java.nio.file.spi.FileSystemProvider; 60 import java.nio.file.spi.FileTypeDetector; 61 import java.security.AccessController; 62 import java.security.PrivilegedAction; 63 import java.util.ArrayList; 64 import java.util.Arrays; 65 import java.util.Collections; 66 import java.util.EnumSet; 67 import java.util.HashSet; 68 import java.util.Iterator; 69 import java.util.List; 70 import java.util.Map; 71 import java.util.Objects; 72 import java.util.ServiceLoader; 73 import java.util.Set; 74 import java.util.Spliterator; 75 import java.util.Spliterators; 76 import java.util.function.BiPredicate; 77 import java.util.stream.Stream; 78 import java.util.stream.StreamSupport; 79 80 import 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>. 1612 * 1613 * @apiNote 1614 * The exact definition of hidden is platform or provider dependent. On UNIX 1615 * for example a file is considered to be hidden if its name begins with a 1616 * period character ('.'). On Windows a file is considered hidden if the DOS 1617 * {@link DosFileAttributes#isHidden hidden} attribute is set. 1618 * 1619 * <p> Depending on the implementation this method may require to access 1620 * the file system to determine if the file is considered hidden. 1621 * 1622 * @param path 1623 * the path to the file to test 1624 * 1625 * @return {@code true} if the file is considered hidden 1626 * 1627 * @throws IOException 1628 * if an I/O error occurs 1629 * @throws SecurityException 1630 * In the case of the default provider, and a security manager is 1631 * installed, the {@link SecurityManager#checkRead(String) checkRead} 1632 * method is invoked to check read access to the file. 1633 */ 1634 public static boolean isHidden(Path path) throws IOException { 1635 return provider(path).isHidden(path); 1636 } 1637 1638 // lazy loading of default and installed file type detectors 1639 private static class FileTypeDetectors{ 1640 static final FileTypeDetector defaultFileTypeDetector = 1641 createDefaultFileTypeDetector(); 1642 static final List<FileTypeDetector> installedDetectors = 1643 loadInstalledDetectors(); 1644 1645 // creates the default file type detector 1646 private static FileTypeDetector createDefaultFileTypeDetector() { 1647 return AccessController 1648 .doPrivileged(new PrivilegedAction<>() { 1649 @Override public FileTypeDetector run() { 1650 return sun.nio.fs.DefaultFileTypeDetector.create(); 1651 }}); 1652 } 1653 1654 // loads all installed file type detectors 1655 private static List<FileTypeDetector> loadInstalledDetectors() { 1656 return AccessController 1657 .doPrivileged(new PrivilegedAction<>() { 1658 @Override public List<FileTypeDetector> run() { 1659 List<FileTypeDetector> list = new ArrayList<>(); 1660 ServiceLoader<FileTypeDetector> loader = ServiceLoader 1661 .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader()); 1662 for (FileTypeDetector detector: loader) { 1663 list.add(detector); 1664 } 1665 return list; 1666 }}); 1667 } 1668 } 1669 1670 /** 1671 * Probes the content type of a file. 1672 * 1673 * <p> This method uses the installed {@link FileTypeDetector} implementations 1674 * to probe the given file to determine its content type. Each file type 1675 * detector's {@link FileTypeDetector#probeContentType probeContentType} is 1676 * invoked, in turn, to probe the file type. If the file is recognized then 1677 * the content type is returned. If the file is not recognized by any of the 1678 * installed file type detectors then a system-default file type detector is 1679 * invoked to guess the content type. 1680 * 1681 * <p> A given invocation of the Java virtual machine maintains a system-wide 1682 * list of file type detectors. Installed file type detectors are loaded 1683 * using the service-provider loading facility defined by the {@link ServiceLoader} 1684 * class. Installed file type detectors are loaded using the system class 1685 * loader. If the system class loader cannot be found then the platform class 1686 * loader is used. File type detectors are typically installed 1687 * by placing them in a JAR file on the application class path, 1688 * the JAR file contains a provider-configuration file 1689 * named {@code java.nio.file.spi.FileTypeDetector} in the resource directory 1690 * {@code META-INF/services}, and the file lists one or more fully-qualified 1691 * names of concrete subclass of {@code FileTypeDetector } that have a zero 1692 * argument constructor. If the process of locating or instantiating the 1693 * installed file type detectors fails then an unspecified error is thrown. 1694 * The ordering that installed providers are located is implementation 1695 * specific. 1696 * 1697 * <p> The return value of this method is the string form of the value of a 1698 * Multipurpose Internet Mail Extension (MIME) content type as 1699 * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: 1700 * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet 1701 * Message Bodies</i></a>. The string is guaranteed to be parsable according 1702 * to the grammar in the RFC. 1703 * 1704 * @param path 1705 * the path to the file to probe 1706 * 1707 * @return The content type of the file, or {@code null} if the content 1708 * type cannot be determined 1709 * 1710 * @throws IOException 1711 * if an I/O error occurs 1712 * @throws SecurityException 1713 * If a security manager is installed and it denies an unspecified 1714 * permission required by a file type detector implementation. 1715 */ 1716 public static String probeContentType(Path path) 1717 throws IOException 1718 { 1719 // try installed file type detectors 1720 for (FileTypeDetector detector: FileTypeDetectors.installedDetectors) { 1721 String result = detector.probeContentType(path); 1722 if (result != null) 1723 return result; 1724 } 1725 1726 // fallback to default 1727 return FileTypeDetectors.defaultFileTypeDetector.probeContentType(path); 1728 } 1729 1730 // -- File Attributes -- 1731 1732 /** 1733 * Returns a file attribute view of a given type. 1734 * 1735 * <p> A file attribute view provides a read-only or updatable view of a 1736 * set of file attributes. This method is intended to be used where the file 1737 * attribute view defines type-safe methods to read or update the file 1738 * attributes. The {@code type} parameter is the type of the attribute view 1739 * required and the method returns an instance of that type if supported. 1740 * The {@link BasicFileAttributeView} type supports access to the basic 1741 * attributes of a file. Invoking this method to select a file attribute 1742 * view of that type will always return an instance of that class. 1743 * 1744 * <p> The {@code options} array may be used to indicate how symbolic links 1745 * are handled by the resulting file attribute view for the case that the 1746 * file is a symbolic link. By default, symbolic links are followed. If the 1747 * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then 1748 * symbolic links are not followed. This option is ignored by implementations 1749 * that do not support symbolic links. 1750 * 1751 * <p> <b>Usage Example:</b> 1752 * Suppose we want read or set a file's ACL, if supported: 1753 * <pre> 1754 * Path path = ... 1755 * AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); 1756 * if (view != null) { 1757 * List<AclEntry> acl = view.getAcl(); 1758 * : 1759 * } 1760 * </pre> 1761 * 1762 * @param <V> 1763 * The {@code FileAttributeView} type 1764 * @param path 1765 * the path to the file 1766 * @param type 1767 * the {@code Class} object corresponding to the file attribute view 1768 * @param options 1769 * options indicating how symbolic links are handled 1770 * 1771 * @return a file attribute view of the specified type, or {@code null} if 1772 * the attribute view type is not available 1773 */ 1774 public static <V extends FileAttributeView> V getFileAttributeView(Path path, 1775 Class<V> type, 1776 LinkOption... options) 1777 { 1778 return provider(path).getFileAttributeView(path, type, options); 1779 } 1780 1781 /** 1782 * Reads a file's attributes as a bulk operation. 1783 * 1784 * <p> The {@code type} parameter is the type of the attributes required 1785 * and this method returns an instance of that type if supported. All 1786 * implementations support a basic set of file attributes and so invoking 1787 * this method with a {@code type} parameter of {@code 1788 * BasicFileAttributes.class} will not throw {@code 1789 * UnsupportedOperationException}. 1790 * 1791 * <p> The {@code options} array may be used to indicate how symbolic links 1792 * are handled for the case that the file is a symbolic link. By default, 1793 * symbolic links are followed and the file attribute of the final target 1794 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1795 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1796 * 1797 * <p> It is implementation specific if all file attributes are read as an 1798 * atomic operation with respect to other file system operations. 1799 * 1800 * <p> <b>Usage Example:</b> 1801 * Suppose we want to read a file's attributes in bulk: 1802 * <pre> 1803 * Path path = ... 1804 * BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 1805 * </pre> 1806 * Alternatively, suppose we want to read file's POSIX attributes without 1807 * following symbolic links: 1808 * <pre> 1809 * PosixFileAttributes attrs = 1810 * Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS); 1811 * </pre> 1812 * 1813 * @param <A> 1814 * The {@code BasicFileAttributes} type 1815 * @param path 1816 * the path to the file 1817 * @param type 1818 * the {@code Class} of the file attributes required 1819 * to read 1820 * @param options 1821 * options indicating how symbolic links are handled 1822 * 1823 * @return the file attributes 1824 * 1825 * @throws UnsupportedOperationException 1826 * if an attributes of the given type are not supported 1827 * @throws IOException 1828 * if an I/O error occurs 1829 * @throws SecurityException 1830 * In the case of the default provider, a security manager is 1831 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1832 * method is invoked to check read access to the file. If this 1833 * method is invoked to read security sensitive attributes then the 1834 * security manager may be invoke to check for additional permissions. 1835 */ 1836 public static <A extends BasicFileAttributes> A readAttributes(Path path, 1837 Class<A> type, 1838 LinkOption... options) 1839 throws IOException 1840 { 1841 return provider(path).readAttributes(path, type, options); 1842 } 1843 1844 /** 1845 * Sets the value of a file attribute. 1846 * 1847 * <p> The {@code attribute} parameter identifies the attribute to be set 1848 * and takes the form: 1849 * <blockquote> 1850 * [<i>view-name</i><b>:</b>]<i>attribute-name</i> 1851 * </blockquote> 1852 * where square brackets [...] delineate an optional component and the 1853 * character {@code ':'} stands for itself. 1854 * 1855 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1856 * FileAttributeView} that identifies a set of file attributes. If not 1857 * specified then it defaults to {@code "basic"}, the name of the file 1858 * attribute view that identifies the basic set of file attributes common to 1859 * many file systems. <i>attribute-name</i> is the name of the attribute 1860 * within the set. 1861 * 1862 * <p> The {@code options} array may be used to indicate how symbolic links 1863 * are handled for the case that the file is a symbolic link. By default, 1864 * symbolic links are followed and the file attribute of the final target 1865 * of the link is set. If the option {@link LinkOption#NOFOLLOW_LINKS 1866 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1867 * 1868 * <p> <b>Usage Example:</b> 1869 * Suppose we want to set the DOS "hidden" attribute: 1870 * <pre> 1871 * Path path = ... 1872 * Files.setAttribute(path, "dos:hidden", true); 1873 * </pre> 1874 * 1875 * @param path 1876 * the path to the file 1877 * @param attribute 1878 * the attribute to set 1879 * @param value 1880 * the attribute value 1881 * @param options 1882 * options indicating how symbolic links are handled 1883 * 1884 * @return the given path 1885 * 1886 * @throws UnsupportedOperationException 1887 * if the attribute view is not available 1888 * @throws IllegalArgumentException 1889 * if the attribute name is not specified, or is not recognized, or 1890 * the attribute value is of the correct type but has an 1891 * inappropriate value 1892 * @throws ClassCastException 1893 * if the attribute value is not of the expected type or is a 1894 * collection containing elements that are not of the expected 1895 * type 1896 * @throws IOException 1897 * if an I/O error occurs 1898 * @throws SecurityException 1899 * In the case of the default provider, and a security manager is 1900 * installed, its {@link SecurityManager#checkWrite(String) checkWrite} 1901 * method denies write access to the file. If this method is invoked 1902 * to set security sensitive attributes then the security manager 1903 * may be invoked to check for additional permissions. 1904 */ 1905 public static Path setAttribute(Path path, String attribute, Object value, 1906 LinkOption... options) 1907 throws IOException 1908 { 1909 provider(path).setAttribute(path, attribute, value, options); 1910 return path; 1911 } 1912 1913 /** 1914 * Reads the value of a file attribute. 1915 * 1916 * <p> The {@code attribute} parameter identifies the attribute to be read 1917 * and takes the form: 1918 * <blockquote> 1919 * [<i>view-name</i><b>:</b>]<i>attribute-name</i> 1920 * </blockquote> 1921 * where square brackets [...] delineate an optional component and the 1922 * character {@code ':'} stands for itself. 1923 * 1924 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1925 * FileAttributeView} that identifies a set of file attributes. If not 1926 * specified then it defaults to {@code "basic"}, the name of the file 1927 * attribute view that identifies the basic set of file attributes common to 1928 * many file systems. <i>attribute-name</i> is the name of the attribute. 1929 * 1930 * <p> The {@code options} array may be used to indicate how symbolic links 1931 * are handled for the case that the file is a symbolic link. By default, 1932 * symbolic links are followed and the file attribute of the final target 1933 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 1934 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 1935 * 1936 * <p> <b>Usage Example:</b> 1937 * Suppose we require the user ID of the file owner on a system that 1938 * supports a "{@code unix}" view: 1939 * <pre> 1940 * Path path = ... 1941 * int uid = (Integer)Files.getAttribute(path, "unix:uid"); 1942 * </pre> 1943 * 1944 * @param path 1945 * the path to the file 1946 * @param attribute 1947 * the attribute to read 1948 * @param options 1949 * options indicating how symbolic links are handled 1950 * 1951 * @return the attribute value 1952 * 1953 * @throws UnsupportedOperationException 1954 * if the attribute view is not available 1955 * @throws IllegalArgumentException 1956 * if the attribute name is not specified or is not recognized 1957 * @throws IOException 1958 * if an I/O error occurs 1959 * @throws SecurityException 1960 * In the case of the default provider, and a security manager is 1961 * installed, its {@link SecurityManager#checkRead(String) checkRead} 1962 * method denies read access to the file. If this method is invoked 1963 * to read security sensitive attributes then the security manager 1964 * may be invoked to check for additional permissions. 1965 */ 1966 public static Object getAttribute(Path path, String attribute, 1967 LinkOption... options) 1968 throws IOException 1969 { 1970 // only one attribute should be read 1971 if (attribute.indexOf('*') >= 0 || attribute.indexOf(',') >= 0) 1972 throw new IllegalArgumentException(attribute); 1973 Map<String,Object> map = readAttributes(path, attribute, options); 1974 assert map.size() == 1; 1975 String name; 1976 int pos = attribute.indexOf(':'); 1977 if (pos == -1) { 1978 name = attribute; 1979 } else { 1980 name = (pos == attribute.length()) ? "" : attribute.substring(pos+1); 1981 } 1982 return map.get(name); 1983 } 1984 1985 /** 1986 * Reads a set of file attributes as a bulk operation. 1987 * 1988 * <p> The {@code attributes} parameter identifies the attributes to be read 1989 * and takes the form: 1990 * <blockquote> 1991 * [<i>view-name</i><b>:</b>]<i>attribute-list</i> 1992 * </blockquote> 1993 * where square brackets [...] delineate an optional component and the 1994 * character {@code ':'} stands for itself. 1995 * 1996 * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link 1997 * FileAttributeView} that identifies a set of file attributes. If not 1998 * specified then it defaults to {@code "basic"}, the name of the file 1999 * attribute view that identifies the basic set of file attributes common to 2000 * many file systems. 2001 * 2002 * <p> The <i>attribute-list</i> component is a comma separated list of 2003 * one or more names of attributes to read. If the list contains the value 2004 * {@code "*"} then all attributes are read. Attributes that are not supported 2005 * are ignored and will not be present in the returned map. It is 2006 * implementation specific if all attributes are read as an atomic operation 2007 * with respect to other file system operations. 2008 * 2009 * <p> The following examples demonstrate possible values for the {@code 2010 * attributes} parameter: 2011 * 2012 * <table class="striped" style="text-align: left; margin-left:2em"> 2013 * <caption style="display:none">Possible values</caption> 2014 * <thead> 2015 * <tr> 2016 * <th scope="col">Example 2017 * <th scope="col">Description 2018 * </thead> 2019 * <tbody> 2020 * <tr> 2021 * <th scope="row"> {@code "*"} </th> 2022 * <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td> 2023 * </tr> 2024 * <tr> 2025 * <th scope="row"> {@code "size,lastModifiedTime,lastAccessTime"} </th> 2026 * <td> Reads the file size, last modified time, and last access time 2027 * attributes. </td> 2028 * </tr> 2029 * <tr> 2030 * <th scope="row"> {@code "posix:*"} </th> 2031 * <td> Read all {@link PosixFileAttributes POSIX-file-attributes}. </td> 2032 * </tr> 2033 * <tr> 2034 * <th scope="row"> {@code "posix:permissions,owner,size"} </th> 2035 * <td> Reads the POSIX file permissions, owner, and file size. </td> 2036 * </tr> 2037 * </tbody> 2038 * </table> 2039 * 2040 * <p> The {@code options} array may be used to indicate how symbolic links 2041 * are handled for the case that the file is a symbolic link. By default, 2042 * symbolic links are followed and the file attribute of the final target 2043 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2044 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2045 * 2046 * @param path 2047 * the path to the file 2048 * @param attributes 2049 * the attributes to read 2050 * @param options 2051 * options indicating how symbolic links are handled 2052 * 2053 * @return a map of the attributes returned; The map's keys are the 2054 * attribute names, its values are the attribute values 2055 * 2056 * @throws UnsupportedOperationException 2057 * if the attribute view is not available 2058 * @throws IllegalArgumentException 2059 * if no attributes are specified or an unrecognized attribute is 2060 * specified 2061 * @throws IOException 2062 * if an I/O error occurs 2063 * @throws SecurityException 2064 * In the case of the default provider, and a security manager is 2065 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2066 * method denies read access to the file. If this method is invoked 2067 * to read security sensitive attributes then the security manager 2068 * may be invoke to check for additional permissions. 2069 */ 2070 public static Map<String,Object> readAttributes(Path path, String attributes, 2071 LinkOption... options) 2072 throws IOException 2073 { 2074 return provider(path).readAttributes(path, attributes, options); 2075 } 2076 2077 /** 2078 * Returns a file's POSIX file permissions. 2079 * 2080 * <p> The {@code path} parameter is associated with a {@code FileSystem} 2081 * that supports the {@link PosixFileAttributeView}. This attribute view 2082 * provides access to file attributes commonly associated with files on file 2083 * systems used by operating systems that implement the Portable Operating 2084 * System Interface (POSIX) family of standards. 2085 * 2086 * <p> The {@code options} array may be used to indicate how symbolic links 2087 * are handled for the case that the file is a symbolic link. By default, 2088 * symbolic links are followed and the file attribute of the final target 2089 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2090 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2091 * 2092 * @param path 2093 * the path to the file 2094 * @param options 2095 * options indicating how symbolic links are handled 2096 * 2097 * @return the file permissions 2098 * 2099 * @throws UnsupportedOperationException 2100 * if the associated file system does not support the {@code 2101 * PosixFileAttributeView} 2102 * @throws IOException 2103 * if an I/O error occurs 2104 * @throws SecurityException 2105 * In the case of the default provider, a security manager is 2106 * installed, and it denies 2107 * {@link RuntimePermission}{@code ("accessUserInformation")} 2108 * or its {@link SecurityManager#checkRead(String) checkRead} method 2109 * denies read access to the file. 2110 */ 2111 public static Set<PosixFilePermission> getPosixFilePermissions(Path path, 2112 LinkOption... options) 2113 throws IOException 2114 { 2115 return readAttributes(path, PosixFileAttributes.class, options).permissions(); 2116 } 2117 2118 /** 2119 * Sets a file's POSIX permissions. 2120 * 2121 * <p> The {@code path} parameter is associated with a {@code FileSystem} 2122 * that supports the {@link PosixFileAttributeView}. This attribute view 2123 * provides access to file attributes commonly associated with files on file 2124 * systems used by operating systems that implement the Portable Operating 2125 * System Interface (POSIX) family of standards. 2126 * 2127 * @param path 2128 * The path to the file 2129 * @param perms 2130 * The new set of permissions 2131 * 2132 * @return The given path 2133 * 2134 * @throws UnsupportedOperationException 2135 * if the associated file system does not support the {@code 2136 * PosixFileAttributeView} 2137 * @throws ClassCastException 2138 * if the sets contains elements that are not of type {@code 2139 * PosixFilePermission} 2140 * @throws IOException 2141 * if an I/O error occurs 2142 * @throws SecurityException 2143 * In the case of the default provider, and a security manager is 2144 * installed, it denies 2145 * {@link RuntimePermission}{@code ("accessUserInformation")} 2146 * or its {@link SecurityManager#checkWrite(String) checkWrite} 2147 * method denies write access to the file. 2148 */ 2149 public static Path setPosixFilePermissions(Path path, 2150 Set<PosixFilePermission> perms) 2151 throws IOException 2152 { 2153 PosixFileAttributeView view = 2154 getFileAttributeView(path, PosixFileAttributeView.class); 2155 if (view == null) 2156 throw new UnsupportedOperationException(); 2157 view.setPermissions(perms); 2158 return path; 2159 } 2160 2161 /** 2162 * Returns the owner of a file. 2163 * 2164 * <p> The {@code path} parameter is associated with a file system that 2165 * supports {@link FileOwnerAttributeView}. This file attribute view provides 2166 * access to a file attribute that is the owner of the file. 2167 * 2168 * @param path 2169 * The path to the file 2170 * @param options 2171 * options indicating how symbolic links are handled 2172 * 2173 * @return A user principal representing the owner of the file 2174 * 2175 * @throws UnsupportedOperationException 2176 * if the associated file system does not support the {@code 2177 * FileOwnerAttributeView} 2178 * @throws IOException 2179 * if an I/O error occurs 2180 * @throws SecurityException 2181 * In the case of the default provider, and a security manager is 2182 * installed, it denies 2183 * {@link RuntimePermission}{@code ("accessUserInformation")} 2184 * or its {@link SecurityManager#checkRead(String) checkRead} method 2185 * denies read access to the file. 2186 */ 2187 public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException { 2188 FileOwnerAttributeView view = 2189 getFileAttributeView(path, FileOwnerAttributeView.class, options); 2190 if (view == null) 2191 throw new UnsupportedOperationException(); 2192 return view.getOwner(); 2193 } 2194 2195 /** 2196 * Updates the file owner. 2197 * 2198 * <p> The {@code path} parameter is associated with a file system that 2199 * supports {@link FileOwnerAttributeView}. This file attribute view provides 2200 * access to a file attribute that is the owner of the file. 2201 * 2202 * <p> <b>Usage Example:</b> 2203 * Suppose we want to make "joe" the owner of a file: 2204 * <pre> 2205 * Path path = ... 2206 * UserPrincipalLookupService lookupService = 2207 * provider(path).getUserPrincipalLookupService(); 2208 * UserPrincipal joe = lookupService.lookupPrincipalByName("joe"); 2209 * Files.setOwner(path, joe); 2210 * </pre> 2211 * 2212 * @param path 2213 * The path to the file 2214 * @param owner 2215 * The new file owner 2216 * 2217 * @return The given path 2218 * 2219 * @throws UnsupportedOperationException 2220 * if the associated file system does not support the {@code 2221 * FileOwnerAttributeView} 2222 * @throws IOException 2223 * if an I/O error occurs 2224 * @throws SecurityException 2225 * In the case of the default provider, and a security manager is 2226 * installed, it denies 2227 * {@link RuntimePermission}{@code ("accessUserInformation")} 2228 * or its {@link SecurityManager#checkWrite(String) checkWrite} 2229 * method denies write access to the file. 2230 * 2231 * @see FileSystem#getUserPrincipalLookupService 2232 * @see java.nio.file.attribute.UserPrincipalLookupService 2233 */ 2234 public static Path setOwner(Path path, UserPrincipal owner) 2235 throws IOException 2236 { 2237 FileOwnerAttributeView view = 2238 getFileAttributeView(path, FileOwnerAttributeView.class); 2239 if (view == null) 2240 throw new UnsupportedOperationException(); 2241 view.setOwner(owner); 2242 return path; 2243 } 2244 2245 /** 2246 * Tests whether a file is a symbolic link. 2247 * 2248 * <p> Where it is required to distinguish an I/O exception from the case 2249 * that the file is not a symbolic link then the file attributes can be 2250 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2251 * readAttributes} method and the file type tested with the {@link 2252 * BasicFileAttributes#isSymbolicLink} method. 2253 * 2254 * @param path The path to the file 2255 * 2256 * @return {@code true} if the file is a symbolic link; {@code false} if 2257 * the file does not exist, is not a symbolic link, or it cannot 2258 * be determined if the file is a symbolic link or not. 2259 * 2260 * @throws SecurityException 2261 * In the case of the default provider, and a security manager is 2262 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2263 * method denies read access to the file. 2264 */ 2265 public static boolean isSymbolicLink(Path path) { 2266 try { 2267 return readAttributes(path, 2268 BasicFileAttributes.class, 2269 LinkOption.NOFOLLOW_LINKS).isSymbolicLink(); 2270 } catch (IOException ioe) { 2271 return false; 2272 } 2273 } 2274 2275 /** 2276 * Tests whether a file is a directory. 2277 * 2278 * <p> The {@code options} array may be used to indicate how symbolic links 2279 * are handled for the case that the file is a symbolic link. By default, 2280 * symbolic links are followed and the file attribute of the final target 2281 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2282 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2283 * 2284 * <p> Where it is required to distinguish an I/O exception from the case 2285 * that the file is not a directory then the file attributes can be 2286 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2287 * readAttributes} method and the file type tested with the {@link 2288 * BasicFileAttributes#isDirectory} method. 2289 * 2290 * @param path 2291 * the path to the file to test 2292 * @param options 2293 * options indicating how symbolic links are handled 2294 * 2295 * @return {@code true} if the file is a directory; {@code false} if 2296 * the file does not exist, is not a directory, or it cannot 2297 * be determined if the file is a directory or not. 2298 * 2299 * @throws SecurityException 2300 * In the case of the default provider, and a security manager is 2301 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2302 * method denies read access to the file. 2303 */ 2304 public static boolean isDirectory(Path path, LinkOption... options) { 2305 if (options.length == 0) { 2306 FileSystemProvider provider = provider(path); 2307 if (provider instanceof AbstractFileSystemProvider) 2308 return ((AbstractFileSystemProvider)provider).isDirectory(path); 2309 } 2310 2311 try { 2312 return readAttributes(path, BasicFileAttributes.class, options).isDirectory(); 2313 } catch (IOException ioe) { 2314 return false; 2315 } 2316 } 2317 2318 /** 2319 * Tests whether a file is a regular file with opaque content. 2320 * 2321 * <p> The {@code options} array may be used to indicate how symbolic links 2322 * are handled for the case that the file is a symbolic link. By default, 2323 * symbolic links are followed and the file attribute of the final target 2324 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2325 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2326 * 2327 * <p> Where it is required to distinguish an I/O exception from the case 2328 * that the file is not a regular file then the file attributes can be 2329 * read with the {@link #readAttributes(Path,Class,LinkOption[]) 2330 * readAttributes} method and the file type tested with the {@link 2331 * BasicFileAttributes#isRegularFile} method. 2332 * 2333 * @param path 2334 * the path to the file 2335 * @param options 2336 * options indicating how symbolic links are handled 2337 * 2338 * @return {@code true} if the file is a regular file; {@code false} if 2339 * the file does not exist, is not a regular file, or it 2340 * cannot be determined if the file is a regular file or not. 2341 * 2342 * @throws SecurityException 2343 * In the case of the default provider, and a security manager is 2344 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2345 * method denies read access to the file. 2346 */ 2347 public static boolean isRegularFile(Path path, LinkOption... options) { 2348 if (options.length == 0) { 2349 FileSystemProvider provider = provider(path); 2350 if (provider instanceof AbstractFileSystemProvider) 2351 return ((AbstractFileSystemProvider)provider).isRegularFile(path); 2352 } 2353 2354 try { 2355 return readAttributes(path, BasicFileAttributes.class, options).isRegularFile(); 2356 } catch (IOException ioe) { 2357 return false; 2358 } 2359 } 2360 2361 /** 2362 * Returns a file's last modified time. 2363 * 2364 * <p> The {@code options} array may be used to indicate how symbolic links 2365 * are handled for the case that the file is a symbolic link. By default, 2366 * symbolic links are followed and the file attribute of the final target 2367 * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS 2368 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2369 * 2370 * @param path 2371 * the path to the file 2372 * @param options 2373 * options indicating how symbolic links are handled 2374 * 2375 * @return a {@code FileTime} representing the time the file was last 2376 * modified, or an implementation specific default when a time 2377 * stamp to indicate the time of last modification is not supported 2378 * by the file system 2379 * 2380 * @throws IOException 2381 * if an I/O error occurs 2382 * @throws SecurityException 2383 * In the case of the default provider, and a security manager is 2384 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2385 * method denies read access to the file. 2386 * 2387 * @see BasicFileAttributes#lastModifiedTime 2388 */ 2389 public static FileTime getLastModifiedTime(Path path, LinkOption... options) 2390 throws IOException 2391 { 2392 return readAttributes(path, BasicFileAttributes.class, options).lastModifiedTime(); 2393 } 2394 2395 /** 2396 * Updates a file's last modified time attribute. The file time is converted 2397 * to the epoch and precision supported by the file system. Converting from 2398 * finer to coarser granularities result in precision loss. The behavior of 2399 * this method when attempting to set the last modified time when it is not 2400 * supported by the file system or is outside the range supported by the 2401 * underlying file store is not defined. It may or not fail by throwing an 2402 * {@code IOException}. 2403 * 2404 * <p> <b>Usage Example:</b> 2405 * Suppose we want to set the last modified time to the current time: 2406 * <pre> 2407 * Path path = ... 2408 * FileTime now = FileTime.fromMillis(System.currentTimeMillis()); 2409 * Files.setLastModifiedTime(path, now); 2410 * </pre> 2411 * 2412 * @param path 2413 * the path to the file 2414 * @param time 2415 * the new last modified time 2416 * 2417 * @return the given path 2418 * 2419 * @throws IOException 2420 * if an I/O error occurs 2421 * @throws SecurityException 2422 * In the case of the default provider, and a security manager is 2423 * installed, its {@link SecurityManager#checkWrite(String) 2424 * checkWrite} method denies write access to the file. 2425 * 2426 * @see BasicFileAttributeView#setTimes 2427 */ 2428 public static Path setLastModifiedTime(Path path, FileTime time) 2429 throws IOException 2430 { 2431 getFileAttributeView(path, BasicFileAttributeView.class) 2432 .setTimes(Objects.requireNonNull(time), null, null); 2433 return path; 2434 } 2435 2436 /** 2437 * Returns the size of a file (in bytes). The size may differ from the 2438 * actual size on the file system due to compression, support for sparse 2439 * files, or other reasons. The size of files that are not {@link 2440 * #isRegularFile regular} files is implementation specific and 2441 * therefore unspecified. 2442 * 2443 * @param path 2444 * the path to the file 2445 * 2446 * @return the file size, in bytes 2447 * 2448 * @throws IOException 2449 * if an I/O error occurs 2450 * @throws SecurityException 2451 * In the case of the default provider, and a security manager is 2452 * installed, its {@link SecurityManager#checkRead(String) checkRead} 2453 * method denies read access to the file. 2454 * 2455 * @see BasicFileAttributes#size 2456 */ 2457 public static long size(Path path) throws IOException { 2458 return readAttributes(path, BasicFileAttributes.class).size(); 2459 } 2460 2461 // -- Accessibility -- 2462 2463 /** 2464 * Returns {@code false} if NOFOLLOW_LINKS is present. 2465 */ 2466 private static boolean followLinks(LinkOption... options) { 2467 boolean followLinks = true; 2468 for (LinkOption opt: options) { 2469 if (opt == LinkOption.NOFOLLOW_LINKS) { 2470 followLinks = false; 2471 continue; 2472 } 2473 if (opt == null) 2474 throw new NullPointerException(); 2475 throw new AssertionError("Should not get here"); 2476 } 2477 return followLinks; 2478 } 2479 2480 /** 2481 * Tests whether a file exists. 2482 * 2483 * <p> The {@code options} parameter may be used to indicate how symbolic links 2484 * are handled for the case that the file is a symbolic link. By default, 2485 * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS 2486 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2487 * 2488 * <p> Note that the result of this method is immediately outdated. If this 2489 * method indicates the file exists then there is no guarantee that a 2490 * subsequent access will succeed. Care should be taken when using this 2491 * method in security sensitive applications. 2492 * 2493 * @param path 2494 * the path to the file to test 2495 * @param options 2496 * options indicating how symbolic links are handled 2497 * . 2498 * @return {@code true} if the file exists; {@code false} if the file does 2499 * not exist or its existence cannot be determined. 2500 * 2501 * @throws SecurityException 2502 * In the case of the default provider, the {@link 2503 * SecurityManager#checkRead(String)} is invoked to check 2504 * read access to the file. 2505 * 2506 * @see #notExists 2507 */ 2508 public static boolean exists(Path path, LinkOption... options) { 2509 if (options.length == 0) { 2510 FileSystemProvider provider = provider(path); 2511 if (provider instanceof AbstractFileSystemProvider) 2512 return ((AbstractFileSystemProvider)provider).exists(path); 2513 } 2514 2515 try { 2516 if (followLinks(options)) { 2517 provider(path).checkAccess(path); 2518 } else { 2519 // attempt to read attributes without following links 2520 readAttributes(path, BasicFileAttributes.class, 2521 LinkOption.NOFOLLOW_LINKS); 2522 } 2523 // file exists 2524 return true; 2525 } catch (IOException x) { 2526 // does not exist or unable to determine if file exists 2527 return false; 2528 } 2529 2530 } 2531 2532 /** 2533 * Tests whether the file located by this path does not exist. This method 2534 * is intended for cases where it is required to take action when it can be 2535 * confirmed that a file does not exist. 2536 * 2537 * <p> The {@code options} parameter may be used to indicate how symbolic links 2538 * are handled for the case that the file is a symbolic link. By default, 2539 * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS 2540 * NOFOLLOW_LINKS} is present then symbolic links are not followed. 2541 * 2542 * <p> Note that this method is not the complement of the {@link #exists 2543 * exists} method. Where it is not possible to determine if a file exists 2544 * or not then both methods return {@code false}. As with the {@code exists} 2545 * method, the result of this method is immediately outdated. If this 2546 * method indicates the file does exist then there is no guarantee that a 2547 * subsequent attempt to create the file will succeed. Care should be taken 2548 * when using this method in security sensitive applications. 2549 * 2550 * @param path 2551 * the path to the file to test 2552 * @param options 2553 * options indicating how symbolic links are handled 2554 * 2555 * @return {@code true} if the file does not exist; {@code false} if the 2556 * file exists or its existence cannot be determined 2557 * 2558 * @throws SecurityException 2559 * In the case of the default provider, the {@link 2560 * SecurityManager#checkRead(String)} is invoked to check 2561 * read access to the file. 2562 */ 2563 public static boolean notExists(Path path, LinkOption... options) { 2564 try { 2565 if (followLinks(options)) { 2566 provider(path).checkAccess(path); 2567 } else { 2568 // attempt to read attributes without following links 2569 readAttributes(path, BasicFileAttributes.class, 2570 LinkOption.NOFOLLOW_LINKS); 2571 } 2572 // file exists 2573 return false; 2574 } catch (NoSuchFileException x) { 2575 // file confirmed not to exist 2576 return true; 2577 } catch (IOException x) { 2578 return false; 2579 } 2580 } 2581 2582 /** 2583 * Used by isReadable, isWritable, isExecutable to test access to a file. 2584 */ 2585 private static boolean isAccessible(Path path, AccessMode... modes) { 2586 try { 2587 provider(path).checkAccess(path, modes); 2588 return true; 2589 } catch (IOException x) { 2590 return false; 2591 } 2592 } 2593 2594 /** 2595 * Tests whether a file is readable. This method checks that a file exists 2596 * and that this Java virtual machine has appropriate privileges that would 2597 * allow it open the file for reading. Depending on the implementation, this 2598 * method may require to read file permissions, access control lists, or 2599 * other file attributes in order to check the effective access to the file. 2600 * Consequently, this method may not be atomic with respect to other file 2601 * system operations. 2602 * 2603 * <p> Note that the result of this method is immediately outdated, there is 2604 * no guarantee that a subsequent attempt to open the file for reading will 2605 * succeed (or even that it will access the same file). Care should be taken 2606 * when using this method in security sensitive applications. 2607 * 2608 * @param path 2609 * the path to the file to check 2610 * 2611 * @return {@code true} if the file exists and is readable; {@code false} 2612 * if the file does not exist, read access would be denied because 2613 * the Java virtual machine has insufficient privileges, or access 2614 * cannot be determined 2615 * 2616 * @throws SecurityException 2617 * In the case of the default provider, and a security manager is 2618 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2619 * is invoked to check read access to the file. 2620 */ 2621 public static boolean isReadable(Path path) { 2622 return isAccessible(path, AccessMode.READ); 2623 } 2624 2625 /** 2626 * Tests whether a file is writable. This method checks that a file exists 2627 * and that this Java virtual machine has appropriate privileges that would 2628 * allow it open the file for writing. Depending on the implementation, this 2629 * method may require to read file permissions, access control lists, or 2630 * other file attributes in order to check the effective access to the file. 2631 * Consequently, this method may not be atomic with respect to other file 2632 * system operations. 2633 * 2634 * <p> Note that result of this method is immediately outdated, there is no 2635 * guarantee that a subsequent attempt to open the file for writing will 2636 * succeed (or even that it will access the same file). Care should be taken 2637 * when using this method in security sensitive applications. 2638 * 2639 * @param path 2640 * the path to the file to check 2641 * 2642 * @return {@code true} if the file exists and is writable; {@code false} 2643 * if the file does not exist, write access would be denied because 2644 * the Java virtual machine has insufficient privileges, or access 2645 * cannot be determined 2646 * 2647 * @throws SecurityException 2648 * In the case of the default provider, and a security manager is 2649 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2650 * is invoked to check write access to the file. 2651 */ 2652 public static boolean isWritable(Path path) { 2653 return isAccessible(path, AccessMode.WRITE); 2654 } 2655 2656 /** 2657 * Tests whether a file is executable. This method checks that a file exists 2658 * and that this Java virtual machine has appropriate privileges to {@link 2659 * Runtime#exec execute} the file. The semantics may differ when checking 2660 * access to a directory. For example, on UNIX systems, checking for 2661 * execute access checks that the Java virtual machine has permission to 2662 * search the directory in order to access file or subdirectories. 2663 * 2664 * <p> Depending on the implementation, this method may require to read file 2665 * permissions, access control lists, or other file attributes in order to 2666 * check the effective access to the file. Consequently, this method may not 2667 * be atomic with respect to other file system operations. 2668 * 2669 * <p> Note that the result of this method is immediately outdated, there is 2670 * no guarantee that a subsequent attempt to execute the file will succeed 2671 * (or even that it will access the same file). Care should be taken when 2672 * using this method in security sensitive applications. 2673 * 2674 * @param path 2675 * the path to the file to check 2676 * 2677 * @return {@code true} if the file exists and is executable; {@code false} 2678 * if the file does not exist, execute access would be denied because 2679 * the Java virtual machine has insufficient privileges, or access 2680 * cannot be determined 2681 * 2682 * @throws SecurityException 2683 * In the case of the default provider, and a security manager is 2684 * installed, the {@link SecurityManager#checkExec(String) 2685 * checkExec} is invoked to check execute access to the file. 2686 */ 2687 public static boolean isExecutable(Path path) { 2688 return isAccessible(path, AccessMode.EXECUTE); 2689 } 2690 2691 // -- Recursive operations -- 2692 2693 /** 2694 * Walks a file tree. 2695 * 2696 * <p> This method walks a file tree rooted at a given starting file. The 2697 * file tree traversal is <em>depth-first</em> with the given {@link 2698 * FileVisitor} invoked for each file encountered. File tree traversal 2699 * completes when all accessible files in the tree have been visited, or a 2700 * visit method returns a result of {@link FileVisitResult#TERMINATE 2701 * TERMINATE}. Where a visit method terminates due an {@code IOException}, 2702 * an uncaught error, or runtime exception, then the traversal is terminated 2703 * and the error or exception is propagated to the caller of this method. 2704 * 2705 * <p> For each file encountered this method attempts to read its {@link 2706 * java.nio.file.attribute.BasicFileAttributes}. If the file is not a 2707 * directory then the {@link FileVisitor#visitFile visitFile} method is 2708 * invoked with the file attributes. If the file attributes cannot be read, 2709 * due to an I/O exception, then the {@link FileVisitor#visitFileFailed 2710 * visitFileFailed} method is invoked with the I/O exception. 2711 * 2712 * <p> Where the file is a directory, and the directory could not be opened, 2713 * then the {@code visitFileFailed} method is invoked with the I/O exception, 2714 * after which, the file tree walk continues, by default, at the next 2715 * <em>sibling</em> of the directory. 2716 * 2717 * <p> Where the directory is opened successfully, then the entries in the 2718 * directory, and their <em>descendants</em> are visited. When all entries 2719 * have been visited, or an I/O error occurs during iteration of the 2720 * directory, then the directory is closed and the visitor's {@link 2721 * FileVisitor#postVisitDirectory postVisitDirectory} method is invoked. 2722 * The file tree walk then continues, by default, at the next <em>sibling</em> 2723 * of the directory. 2724 * 2725 * <p> By default, symbolic links are not automatically followed by this 2726 * method. If the {@code options} parameter contains the {@link 2727 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are 2728 * followed. When following links, and the attributes of the target cannot 2729 * be read, then this method attempts to get the {@code BasicFileAttributes} 2730 * of the link. If they can be read then the {@code visitFile} method is 2731 * invoked with the attributes of the link (otherwise the {@code visitFileFailed} 2732 * method is invoked as specified above). 2733 * 2734 * <p> If the {@code options} parameter contains the {@link 2735 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then this method keeps 2736 * track of directories visited so that cycles can be detected. A cycle 2737 * arises when there is an entry in a directory that is an ancestor of the 2738 * directory. Cycle detection is done by recording the {@link 2739 * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, 2740 * or if file keys are not available, by invoking the {@link #isSameFile 2741 * isSameFile} method to test if a directory is the same file as an 2742 * ancestor. When a cycle is detected it is treated as an I/O error, and the 2743 * {@link FileVisitor#visitFileFailed visitFileFailed} method is invoked with 2744 * an instance of {@link FileSystemLoopException}. 2745 * 2746 * <p> The {@code maxDepth} parameter is the maximum number of levels of 2747 * directories to visit. A value of {@code 0} means that only the starting 2748 * file is visited, unless denied by the security manager. A value of 2749 * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all 2750 * levels should be visited. The {@code visitFile} method is invoked for all 2751 * files, including directories, encountered at {@code maxDepth}, unless the 2752 * basic file attributes cannot be read, in which case the {@code 2753 * visitFileFailed} method is invoked. 2754 * 2755 * <p> If a visitor returns a result of {@code null} then {@code 2756 * NullPointerException} is thrown. 2757 * 2758 * <p> When a security manager is installed and it denies access to a file 2759 * (or directory), then it is ignored and the visitor is not invoked for 2760 * that file (or directory). 2761 * 2762 * @param start 2763 * the starting file 2764 * @param options 2765 * options to configure the traversal 2766 * @param maxDepth 2767 * the maximum number of directory levels to visit 2768 * @param visitor 2769 * the file visitor to invoke for each file 2770 * 2771 * @return the starting file 2772 * 2773 * @throws IllegalArgumentException 2774 * if the {@code maxDepth} parameter is negative 2775 * @throws SecurityException 2776 * If the security manager denies access to the starting file. 2777 * In the case of the default provider, the {@link 2778 * SecurityManager#checkRead(String) checkRead} method is invoked 2779 * to check read access to the directory. 2780 * @throws IOException 2781 * if an I/O error is thrown by a visitor method 2782 */ 2783 public static Path walkFileTree(Path start, 2784 Set<FileVisitOption> options, 2785 int maxDepth, 2786 FileVisitor<? super Path> visitor) 2787 throws IOException 2788 { 2789 /** 2790 * Create a FileTreeWalker to walk the file tree, invoking the visitor 2791 * for each event. 2792 */ 2793 try (FileTreeWalker walker = new FileTreeWalker(options, maxDepth)) { 2794 FileTreeWalker.Event ev = walker.walk(start); 2795 do { 2796 FileVisitResult result; 2797 switch (ev.type()) { 2798 case ENTRY : 2799 IOException ioe = ev.ioeException(); 2800 if (ioe == null) { 2801 assert ev.attributes() != null; 2802 result = visitor.visitFile(ev.file(), ev.attributes()); 2803 } else { 2804 result = visitor.visitFileFailed(ev.file(), ioe); 2805 } 2806 break; 2807 2808 case START_DIRECTORY : 2809 result = visitor.preVisitDirectory(ev.file(), ev.attributes()); 2810 2811 // if SKIP_SIBLINGS and SKIP_SUBTREE is returned then 2812 // there shouldn't be any more events for the current 2813 // directory. 2814 if (result == FileVisitResult.SKIP_SUBTREE || 2815 result == FileVisitResult.SKIP_SIBLINGS) 2816 walker.pop(); 2817 break; 2818 2819 case END_DIRECTORY : 2820 result = visitor.postVisitDirectory(ev.file(), ev.ioeException()); 2821 2822 // SKIP_SIBLINGS is a no-op for postVisitDirectory 2823 if (result == FileVisitResult.SKIP_SIBLINGS) 2824 result = FileVisitResult.CONTINUE; 2825 break; 2826 2827 default : 2828 throw new AssertionError("Should not get here"); 2829 } 2830 2831 if (Objects.requireNonNull(result) != FileVisitResult.CONTINUE) { 2832 if (result == FileVisitResult.TERMINATE) { 2833 break; 2834 } else if (result == FileVisitResult.SKIP_SIBLINGS) { 2835 walker.skipRemainingSiblings(); 2836 } 2837 } 2838 ev = walker.next(); 2839 } while (ev != null); 2840 } 2841 2842 return start; 2843 } 2844 2845 /** 2846 * Walks a file tree. 2847 * 2848 * <p> This method works as if invoking it were equivalent to evaluating the 2849 * expression: 2850 * <blockquote><pre> 2851 * walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor) 2852 * </pre></blockquote> 2853 * In other words, it does not follow symbolic links, and visits all levels 2854 * of the file tree. 2855 * 2856 * @param start 2857 * the starting file 2858 * @param visitor 2859 * the file visitor to invoke for each file 2860 * 2861 * @return the starting file 2862 * 2863 * @throws SecurityException 2864 * If the security manager denies access to the starting file. 2865 * In the case of the default provider, the {@link 2866 * SecurityManager#checkRead(String) checkRead} method is invoked 2867 * to check read access to the directory. 2868 * @throws IOException 2869 * if an I/O error is thrown by a visitor method 2870 */ 2871 public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) 2872 throws IOException 2873 { 2874 return walkFileTree(start, 2875 EnumSet.noneOf(FileVisitOption.class), 2876 Integer.MAX_VALUE, 2877 visitor); 2878 } 2879 2880 2881 // -- Utility methods for simple usages -- 2882 2883 2884 /** 2885 * Opens a file for reading, returning a {@code BufferedReader} that may be 2886 * used to read text from the file in an efficient manner. Bytes from the 2887 * file are decoded into characters using the specified charset. Reading 2888 * commences at the beginning of the file. 2889 * 2890 * <p> The {@code Reader} methods that read from the file throw {@code 2891 * IOException} if a malformed or unmappable byte sequence is read. 2892 * 2893 * @param path 2894 * the path to the file 2895 * @param cs 2896 * the charset to use for decoding 2897 * 2898 * @return a new buffered reader, with default buffer size, to read text 2899 * from the file 2900 * 2901 * @throws IOException 2902 * if an I/O error occurs opening the file 2903 * @throws SecurityException 2904 * In the case of the default provider, and a security manager is 2905 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2906 * method is invoked to check read access to the file. 2907 * 2908 * @see #readAllLines 2909 */ 2910 public static BufferedReader newBufferedReader(Path path, Charset cs) 2911 throws IOException 2912 { 2913 CharsetDecoder decoder = cs.newDecoder(); 2914 Reader reader = new InputStreamReader(newInputStream(path), decoder); 2915 return new BufferedReader(reader); 2916 } 2917 2918 /** 2919 * Opens a file for reading, returning a {@code BufferedReader} to read text 2920 * from the file in an efficient manner. Bytes from the file are decoded into 2921 * characters using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset 2922 * charset}. 2923 * 2924 * <p> This method works as if invoking it were equivalent to evaluating the 2925 * expression: 2926 * <pre>{@code 2927 * Files.newBufferedReader(path, StandardCharsets.UTF_8) 2928 * }</pre> 2929 * 2930 * @param path 2931 * the path to the file 2932 * 2933 * @return a new buffered reader, with default buffer size, to read text 2934 * from the file 2935 * 2936 * @throws IOException 2937 * if an I/O error occurs opening the file 2938 * @throws SecurityException 2939 * In the case of the default provider, and a security manager is 2940 * installed, the {@link SecurityManager#checkRead(String) checkRead} 2941 * method is invoked to check read access to the file. 2942 * 2943 * @since 1.8 2944 */ 2945 public static BufferedReader newBufferedReader(Path path) throws IOException { 2946 return newBufferedReader(path, StandardCharsets.UTF_8); 2947 } 2948 2949 /** 2950 * Opens or creates a file for writing, returning a {@code BufferedWriter} 2951 * that may be used to write text to the file in an efficient manner. 2952 * The {@code options} parameter specifies how the file is created or 2953 * opened. If no options are present then this method works as if the {@link 2954 * StandardOpenOption#CREATE CREATE}, {@link 2955 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 2956 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 2957 * opens the file for writing, creating the file if it doesn't exist, or 2958 * initially truncating an existing {@link #isRegularFile regular-file} to 2959 * a size of {@code 0} if it exists. 2960 * 2961 * <p> The {@code Writer} methods to write text throw {@code IOException} 2962 * if the text cannot be encoded using the specified charset. 2963 * 2964 * @param path 2965 * the path to the file 2966 * @param cs 2967 * the charset to use for encoding 2968 * @param options 2969 * options specifying how the file is opened 2970 * 2971 * @return a new buffered writer, with default buffer size, to write text 2972 * to the file 2973 * 2974 * @throws IllegalArgumentException 2975 * if {@code options} contains an invalid combination of options 2976 * @throws IOException 2977 * if an I/O error occurs opening or creating the file 2978 * @throws UnsupportedOperationException 2979 * if an unsupported option is specified 2980 * @throws SecurityException 2981 * In the case of the default provider, and a security manager is 2982 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 2983 * method is invoked to check write access to the file. The {@link 2984 * SecurityManager#checkDelete(String) checkDelete} method is 2985 * invoked to check delete access if the file is opened with the 2986 * {@code DELETE_ON_CLOSE} option. 2987 * 2988 * @see #write(Path,Iterable,Charset,OpenOption[]) 2989 */ 2990 public static BufferedWriter newBufferedWriter(Path path, Charset cs, 2991 OpenOption... options) 2992 throws IOException 2993 { 2994 CharsetEncoder encoder = cs.newEncoder(); 2995 Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder); 2996 return new BufferedWriter(writer); 2997 } 2998 2999 /** 3000 * Opens or creates a file for writing, returning a {@code BufferedWriter} 3001 * to write text to the file in an efficient manner. The text is encoded 3002 * into bytes for writing using the {@link StandardCharsets#UTF_8 UTF-8} 3003 * {@link Charset charset}. 3004 * 3005 * <p> This method works as if invoking it were equivalent to evaluating the 3006 * expression: 3007 * <pre>{@code 3008 * Files.newBufferedWriter(path, StandardCharsets.UTF_8, options) 3009 * }</pre> 3010 * 3011 * @param path 3012 * the path to the file 3013 * @param options 3014 * options specifying how the file is opened 3015 * 3016 * @return a new buffered writer, with default buffer size, to write text 3017 * to the file 3018 * 3019 * @throws IllegalArgumentException 3020 * if {@code options} contains an invalid combination of options 3021 * @throws IOException 3022 * if an I/O error occurs opening or creating the file 3023 * @throws UnsupportedOperationException 3024 * if an unsupported option is specified 3025 * @throws SecurityException 3026 * In the case of the default provider, and a security manager is 3027 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3028 * method is invoked to check write access to the file. The {@link 3029 * SecurityManager#checkDelete(String) checkDelete} method is 3030 * invoked to check delete access if the file is opened with the 3031 * {@code DELETE_ON_CLOSE} option. 3032 * 3033 * @since 1.8 3034 */ 3035 public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) 3036 throws IOException 3037 { 3038 return newBufferedWriter(path, StandardCharsets.UTF_8, options); 3039 } 3040 3041 /** 3042 * Copies all bytes from an input stream to a file. On return, the input 3043 * stream will be at end of stream. 3044 * 3045 * <p> By default, the copy fails if the target file already exists or is a 3046 * symbolic link. If the {@link StandardCopyOption#REPLACE_EXISTING 3047 * REPLACE_EXISTING} option is specified, and the target file already exists, 3048 * then it is replaced if it is not a non-empty directory. If the target 3049 * file exists and is a symbolic link, then the symbolic link is replaced. 3050 * In this release, the {@code REPLACE_EXISTING} option is the only option 3051 * required to be supported by this method. Additional options may be 3052 * supported in future releases. 3053 * 3054 * <p> If an I/O error occurs reading from the input stream or writing to 3055 * the file, then it may do so after the target file has been created and 3056 * after some bytes have been read or written. Consequently the input 3057 * stream may not be at end of stream and may be in an inconsistent state. 3058 * It is strongly recommended that the input stream be promptly closed if an 3059 * I/O error occurs. 3060 * 3061 * <p> This method may block indefinitely reading from the input stream (or 3062 * writing to the file). The behavior for the case that the input stream is 3063 * <i>asynchronously closed</i> or the thread interrupted during the copy is 3064 * highly input stream and file system provider specific and therefore not 3065 * specified. 3066 * 3067 * <p> <b>Usage example</b>: Suppose we want to capture a web page and save 3068 * it to a file: 3069 * <pre> 3070 * Path path = ... 3071 * URI u = URI.create("http://www.example.com/"); 3072 * try (InputStream in = u.toURL().openStream()) { 3073 * Files.copy(in, path); 3074 * } 3075 * </pre> 3076 * 3077 * @param in 3078 * the input stream to read from 3079 * @param target 3080 * the path to the file 3081 * @param options 3082 * options specifying how the copy should be done 3083 * 3084 * @return the number of bytes read or written 3085 * 3086 * @throws IOException 3087 * if an I/O error occurs when reading or writing 3088 * @throws FileAlreadyExistsException 3089 * if the target file exists but cannot be replaced because the 3090 * {@code REPLACE_EXISTING} option is not specified <i>(optional 3091 * specific exception)</i> 3092 * @throws DirectoryNotEmptyException 3093 * the {@code REPLACE_EXISTING} option is specified but the file 3094 * cannot be replaced because it is a non-empty directory 3095 * <i>(optional specific exception)</i> * 3096 * @throws UnsupportedOperationException 3097 * if {@code options} contains a copy option that is not supported 3098 * @throws SecurityException 3099 * In the case of the default provider, and a security manager is 3100 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3101 * method is invoked to check write access to the file. Where the 3102 * {@code REPLACE_EXISTING} option is specified, the security 3103 * manager's {@link SecurityManager#checkDelete(String) checkDelete} 3104 * method is invoked to check that an existing file can be deleted. 3105 */ 3106 public static long copy(InputStream in, Path target, CopyOption... options) 3107 throws IOException 3108 { 3109 // ensure not null before opening file 3110 Objects.requireNonNull(in); 3111 3112 // check for REPLACE_EXISTING 3113 boolean replaceExisting = false; 3114 for (CopyOption opt: options) { 3115 if (opt == StandardCopyOption.REPLACE_EXISTING) { 3116 replaceExisting = true; 3117 } else { 3118 if (opt == null) { 3119 throw new NullPointerException("options contains 'null'"); 3120 } else { 3121 throw new UnsupportedOperationException(opt + " not supported"); 3122 } 3123 } 3124 } 3125 3126 // attempt to delete an existing file 3127 SecurityException se = null; 3128 if (replaceExisting) { 3129 try { 3130 deleteIfExists(target); 3131 } catch (SecurityException x) { 3132 se = x; 3133 } 3134 } 3135 3136 // attempt to create target file. If it fails with 3137 // FileAlreadyExistsException then it may be because the security 3138 // manager prevented us from deleting the file, in which case we just 3139 // throw the SecurityException. 3140 OutputStream ostream; 3141 try { 3142 ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW, 3143 StandardOpenOption.WRITE); 3144 } catch (FileAlreadyExistsException x) { 3145 if (se != null) 3146 throw se; 3147 // someone else won the race and created the file 3148 throw x; 3149 } 3150 3151 // do the copy 3152 try (OutputStream out = ostream) { 3153 return in.transferTo(out); 3154 } 3155 } 3156 3157 /** 3158 * Copies all bytes from a file to an output stream. 3159 * 3160 * <p> If an I/O error occurs reading from the file or writing to the output 3161 * stream, then it may do so after some bytes have been read or written. 3162 * Consequently the output stream may be in an inconsistent state. It is 3163 * strongly recommended that the output stream be promptly closed if an I/O 3164 * error occurs. 3165 * 3166 * <p> This method may block indefinitely writing to the output stream (or 3167 * reading from the file). The behavior for the case that the output stream 3168 * is <i>asynchronously closed</i> or the thread interrupted during the copy 3169 * is highly output stream and file system provider specific and therefore 3170 * not specified. 3171 * 3172 * <p> Note that if the given output stream is {@link java.io.Flushable} 3173 * then its {@link java.io.Flushable#flush flush} method may need to invoked 3174 * after this method completes so as to flush any buffered output. 3175 * 3176 * @param source 3177 * the path to the file 3178 * @param out 3179 * the output stream to write to 3180 * 3181 * @return the number of bytes read or written 3182 * 3183 * @throws IOException 3184 * if an I/O error occurs when reading or writing 3185 * @throws SecurityException 3186 * In the case of the default provider, and a security manager is 3187 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3188 * method is invoked to check read access to the file. 3189 */ 3190 public static long copy(Path source, OutputStream out) throws IOException { 3191 // ensure not null before opening file 3192 Objects.requireNonNull(out); 3193 3194 try (InputStream in = newInputStream(source)) { 3195 return in.transferTo(out); 3196 } 3197 } 3198 3199 /** 3200 * The maximum size of array to allocate. 3201 * Some VMs reserve some header words in an array. 3202 * Attempts to allocate larger arrays may result in 3203 * OutOfMemoryError: Requested array size exceeds VM limit 3204 */ 3205 private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; 3206 3207 private static final jdk.internal.access.JavaLangAccess JLA = 3208 jdk.internal.access.SharedSecrets.getJavaLangAccess(); 3209 3210 /** 3211 * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint 3212 * about how many bytes the stream will have. 3213 * 3214 * @param source 3215 * the input stream to read from 3216 * @param initialSize 3217 * the initial size of the byte array to allocate 3218 * 3219 * @return a byte array containing the bytes read from the file 3220 * 3221 * @throws IOException 3222 * if an I/O error occurs reading from the stream 3223 * @throws OutOfMemoryError 3224 * if an array of the required size cannot be allocated 3225 */ 3226 private static byte[] read(InputStream source, int initialSize) throws IOException { 3227 int capacity = initialSize; 3228 byte[] buf = new byte[capacity]; 3229 int nread = 0; 3230 int n; 3231 for (;;) { 3232 // read to EOF which may read more or less than initialSize (eg: file 3233 // is truncated while we are reading) 3234 while ((n = source.read(buf, nread, capacity - nread)) > 0) 3235 nread += n; 3236 3237 // if last call to source.read() returned -1, we are done 3238 // otherwise, try to read one more byte; if that failed we're done too 3239 if (n < 0 || (n = source.read()) < 0) 3240 break; 3241 3242 // one more byte was read; need to allocate a larger buffer 3243 if (capacity <= MAX_BUFFER_SIZE - capacity) { 3244 capacity = Math.max(capacity << 1, BUFFER_SIZE); 3245 } else { 3246 if (capacity == MAX_BUFFER_SIZE) 3247 throw new OutOfMemoryError("Required array size too large"); 3248 capacity = MAX_BUFFER_SIZE; 3249 } 3250 buf = Arrays.copyOf(buf, capacity); 3251 buf[nread++] = (byte)n; 3252 } 3253 return (capacity == nread) ? buf : Arrays.copyOf(buf, nread); 3254 } 3255 3256 /** 3257 * Reads all the bytes from a file. The method ensures that the file is 3258 * closed when all bytes have been read or an I/O error, or other runtime 3259 * exception, is thrown. 3260 * 3261 * <p> Note that this method is intended for simple cases where it is 3262 * convenient to read all bytes into a byte array. It is not intended for 3263 * reading in large files. 3264 * 3265 * @param path 3266 * the path to the file 3267 * 3268 * @return a byte array containing the bytes read from the file 3269 * 3270 * @throws IOException 3271 * if an I/O error occurs reading from the stream 3272 * @throws OutOfMemoryError 3273 * if an array of the required size cannot be allocated, for 3274 * example the file is larger that {@code 2GB} 3275 * @throws SecurityException 3276 * In the case of the default provider, and a security manager is 3277 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3278 * method is invoked to check read access to the file. 3279 */ 3280 public static byte[] readAllBytes(Path path) throws IOException { 3281 try (SeekableByteChannel sbc = Files.newByteChannel(path); 3282 InputStream in = Channels.newInputStream(sbc)) { 3283 if (sbc instanceof FileChannelImpl) 3284 ((FileChannelImpl) sbc).setUninterruptible(); 3285 long size = sbc.size(); 3286 if (size > (long) MAX_BUFFER_SIZE) 3287 throw new OutOfMemoryError("Required array size too large"); 3288 return read(in, (int)size); 3289 } 3290 } 3291 3292 /** 3293 * Reads all content from a file into a string, decoding from bytes to characters 3294 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3295 * The method ensures that the file is closed when all content have been read 3296 * or an I/O error, or other runtime exception, is thrown. 3297 * 3298 * <p> This method is equivalent to: 3299 * {@code readString(path, StandardCharsets.UTF_8) } 3300 * 3301 * @param path the path to the file 3302 * 3303 * @return a String containing the content read from the file 3304 * 3305 * @throws IOException 3306 * if an I/O error occurs reading from the file or a malformed or 3307 * unmappable byte sequence is read 3308 * @throws OutOfMemoryError 3309 * if the file is extremely large, for example larger than {@code 2GB} 3310 * @throws SecurityException 3311 * In the case of the default provider, and a security manager is 3312 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3313 * method is invoked to check read access to the file. 3314 * 3315 * @since 11 3316 */ 3317 public static String readString(Path path) throws IOException { 3318 return readString(path, StandardCharsets.UTF_8); 3319 } 3320 3321 /** 3322 * Reads all characters from a file into a string, decoding from bytes to characters 3323 * using the specified {@linkplain Charset charset}. 3324 * The method ensures that the file is closed when all content have been read 3325 * or an I/O error, or other runtime exception, is thrown. 3326 * 3327 * <p> This method reads all content including the line separators in the middle 3328 * and/or at the end. The resulting string will contain line separators as they 3329 * appear in the file. 3330 * 3331 * @apiNote 3332 * This method is intended for simple cases where it is appropriate and convenient 3333 * to read the content of a file into a String. It is not intended for reading 3334 * very large files. 3335 * 3336 * 3337 * 3338 * @param path the path to the file 3339 * @param cs the charset to use for decoding 3340 * 3341 * @return a String containing the content read from the file 3342 * 3343 * @throws IOException 3344 * if an I/O error occurs reading from the file or a malformed or 3345 * unmappable byte sequence is read 3346 * @throws OutOfMemoryError 3347 * if the file is extremely large, for example larger than {@code 2GB} 3348 * @throws SecurityException 3349 * In the case of the default provider, and a security manager is 3350 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3351 * method is invoked to check read access to the file. 3352 * 3353 * @since 11 3354 */ 3355 public static String readString(Path path, Charset cs) throws IOException { 3356 Objects.requireNonNull(path); 3357 Objects.requireNonNull(cs); 3358 3359 byte[] ba = readAllBytes(path); 3360 return JLA.newStringNoRepl(ba, cs); 3361 } 3362 3363 /** 3364 * Read all lines from a file. This method ensures that the file is 3365 * closed when all bytes have been read or an I/O error, or other runtime 3366 * exception, is thrown. Bytes from the file are decoded into characters 3367 * using the specified charset. 3368 * 3369 * <p> This method recognizes the following as line terminators: 3370 * <ul> 3371 * <li> <code>\u000D</code> followed by <code>\u000A</code>, 3372 * CARRIAGE RETURN followed by LINE FEED </li> 3373 * <li> <code>\u000A</code>, LINE FEED </li> 3374 * <li> <code>\u000D</code>, CARRIAGE RETURN </li> 3375 * </ul> 3376 * <p> Additional Unicode line terminators may be recognized in future 3377 * releases. 3378 * 3379 * <p> Note that this method is intended for simple cases where it is 3380 * convenient to read all lines in a single operation. It is not intended 3381 * for reading in large files. 3382 * 3383 * @param path 3384 * the path to the file 3385 * @param cs 3386 * the charset to use for decoding 3387 * 3388 * @return the lines from the file as a {@code List}; whether the {@code 3389 * List} is modifiable or not is implementation dependent and 3390 * therefore not specified 3391 * 3392 * @throws IOException 3393 * if an I/O error occurs reading from the file or a malformed or 3394 * unmappable byte sequence is read 3395 * @throws SecurityException 3396 * In the case of the default provider, and a security manager is 3397 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3398 * method is invoked to check read access to the file. 3399 * 3400 * @see #newBufferedReader 3401 */ 3402 public static List<String> readAllLines(Path path, Charset cs) throws IOException { 3403 try (BufferedReader reader = newBufferedReader(path, cs)) { 3404 List<String> result = new ArrayList<>(); 3405 for (;;) { 3406 String line = reader.readLine(); 3407 if (line == null) 3408 break; 3409 result.add(line); 3410 } 3411 return result; 3412 } 3413 } 3414 3415 /** 3416 * Read all lines from a file. Bytes from the file are decoded into characters 3417 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3418 * 3419 * <p> This method works as if invoking it were equivalent to evaluating the 3420 * expression: 3421 * <pre>{@code 3422 * Files.readAllLines(path, StandardCharsets.UTF_8) 3423 * }</pre> 3424 * 3425 * @param path 3426 * the path to the file 3427 * 3428 * @return the lines from the file as a {@code List}; whether the {@code 3429 * List} is modifiable or not is implementation dependent and 3430 * therefore not specified 3431 * 3432 * @throws IOException 3433 * if an I/O error occurs reading from the file or a malformed or 3434 * unmappable byte sequence is read 3435 * @throws SecurityException 3436 * In the case of the default provider, and a security manager is 3437 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3438 * method is invoked to check read access to the file. 3439 * 3440 * @since 1.8 3441 */ 3442 public static List<String> readAllLines(Path path) throws IOException { 3443 return readAllLines(path, StandardCharsets.UTF_8); 3444 } 3445 3446 /** 3447 * Writes bytes to a file. The {@code options} parameter specifies how 3448 * the file is created or opened. If no options are present then this method 3449 * works as if the {@link StandardOpenOption#CREATE CREATE}, {@link 3450 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3451 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3452 * opens the file for writing, creating the file if it doesn't exist, or 3453 * initially truncating an existing {@link #isRegularFile regular-file} to 3454 * a size of {@code 0}. All bytes in the byte array are written to the file. 3455 * The method ensures that the file is closed when all bytes have been 3456 * written (or an I/O error or other runtime exception is thrown). If an I/O 3457 * error occurs then it may do so after the file has been created or 3458 * truncated, or after some bytes have been written to the file. 3459 * 3460 * <p> <b>Usage example</b>: By default the method creates a new file or 3461 * overwrites an existing file. Suppose you instead want to append bytes 3462 * to an existing file: 3463 * <pre> 3464 * Path path = ... 3465 * byte[] bytes = ... 3466 * Files.write(path, bytes, StandardOpenOption.APPEND); 3467 * </pre> 3468 * 3469 * @param path 3470 * the path to the file 3471 * @param bytes 3472 * the byte array with the bytes to write 3473 * @param options 3474 * options specifying how the file is opened 3475 * 3476 * @return the path 3477 * 3478 * @throws IllegalArgumentException 3479 * if {@code options} contains an invalid combination of options 3480 * @throws IOException 3481 * if an I/O error occurs writing to or creating the file 3482 * @throws UnsupportedOperationException 3483 * if an unsupported option is specified 3484 * @throws SecurityException 3485 * In the case of the default provider, and a security manager is 3486 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3487 * method is invoked to check write access to the file. The {@link 3488 * SecurityManager#checkDelete(String) checkDelete} method is 3489 * invoked to check delete access if the file is opened with the 3490 * {@code DELETE_ON_CLOSE} option. 3491 */ 3492 public static Path write(Path path, byte[] bytes, OpenOption... options) 3493 throws IOException 3494 { 3495 // ensure bytes is not null before opening file 3496 Objects.requireNonNull(bytes); 3497 3498 try (OutputStream out = Files.newOutputStream(path, options)) { 3499 int len = bytes.length; 3500 int rem = len; 3501 while (rem > 0) { 3502 int n = Math.min(rem, BUFFER_SIZE); 3503 out.write(bytes, (len-rem), n); 3504 rem -= n; 3505 } 3506 } 3507 return path; 3508 } 3509 3510 /** 3511 * Write lines of text to a file. Each line is a char sequence and is 3512 * written to the file in sequence with each line terminated by the 3513 * platform's line separator, as defined by the system property {@code 3514 * line.separator}. Characters are encoded into bytes using the specified 3515 * charset. 3516 * 3517 * <p> The {@code options} parameter specifies how the file is created 3518 * or opened. If no options are present then this method works as if the 3519 * {@link StandardOpenOption#CREATE CREATE}, {@link 3520 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3521 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3522 * opens the file for writing, creating the file if it doesn't exist, or 3523 * initially truncating an existing {@link #isRegularFile regular-file} to 3524 * a size of {@code 0}. The method ensures that the file is closed when all 3525 * lines have been written (or an I/O error or other runtime exception is 3526 * thrown). If an I/O error occurs then it may do so after the file has 3527 * been created or truncated, or after some bytes have been written to the 3528 * file. 3529 * 3530 * @param path 3531 * the path to the file 3532 * @param lines 3533 * an object to iterate over the char sequences 3534 * @param cs 3535 * the charset to use for encoding 3536 * @param options 3537 * options specifying how the file is opened 3538 * 3539 * @return the path 3540 * 3541 * @throws IllegalArgumentException 3542 * if {@code options} contains an invalid combination of options 3543 * @throws IOException 3544 * if an I/O error occurs writing to or creating the file, or the 3545 * text cannot be encoded using the specified charset 3546 * @throws UnsupportedOperationException 3547 * if an unsupported option is specified 3548 * @throws SecurityException 3549 * In the case of the default provider, and a security manager is 3550 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3551 * method is invoked to check write access to the file. The {@link 3552 * SecurityManager#checkDelete(String) checkDelete} method is 3553 * invoked to check delete access if the file is opened with the 3554 * {@code DELETE_ON_CLOSE} option. 3555 */ 3556 public static Path write(Path path, Iterable<? extends CharSequence> lines, 3557 Charset cs, OpenOption... options) 3558 throws IOException 3559 { 3560 // ensure lines is not null before opening file 3561 Objects.requireNonNull(lines); 3562 CharsetEncoder encoder = cs.newEncoder(); 3563 OutputStream out = newOutputStream(path, options); 3564 try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) { 3565 for (CharSequence line: lines) { 3566 writer.append(line); 3567 writer.newLine(); 3568 } 3569 } 3570 return path; 3571 } 3572 3573 /** 3574 * Write lines of text to a file. Characters are encoded into bytes using 3575 * the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3576 * 3577 * <p> This method works as if invoking it were equivalent to evaluating the 3578 * expression: 3579 * <pre>{@code 3580 * Files.write(path, lines, StandardCharsets.UTF_8, options); 3581 * }</pre> 3582 * 3583 * @param path 3584 * the path to the file 3585 * @param lines 3586 * an object to iterate over the char sequences 3587 * @param options 3588 * options specifying how the file is opened 3589 * 3590 * @return the path 3591 * 3592 * @throws IllegalArgumentException 3593 * if {@code options} contains an invalid combination of options 3594 * @throws IOException 3595 * if an I/O error occurs writing to or creating the file, or the 3596 * text cannot be encoded as {@code UTF-8} 3597 * @throws UnsupportedOperationException 3598 * if an unsupported option is specified 3599 * @throws SecurityException 3600 * In the case of the default provider, and a security manager is 3601 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3602 * method is invoked to check write access to the file. The {@link 3603 * SecurityManager#checkDelete(String) checkDelete} method is 3604 * invoked to check delete access if the file is opened with the 3605 * {@code DELETE_ON_CLOSE} option. 3606 * 3607 * @since 1.8 3608 */ 3609 public static Path write(Path path, 3610 Iterable<? extends CharSequence> lines, 3611 OpenOption... options) 3612 throws IOException 3613 { 3614 return write(path, lines, StandardCharsets.UTF_8, options); 3615 } 3616 3617 /** 3618 * Write a {@linkplain java.lang.CharSequence CharSequence} to a file. 3619 * Characters are encoded into bytes using the 3620 * {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}. 3621 * 3622 * <p> This method is equivalent to: 3623 * {@code writeString(path, test, StandardCharsets.UTF_8, options) } 3624 * 3625 * @param path 3626 * the path to the file 3627 * @param csq 3628 * the CharSequence to be written 3629 * @param options 3630 * options specifying how the file is opened 3631 * 3632 * @return the path 3633 * 3634 * @throws IllegalArgumentException 3635 * if {@code options} contains an invalid combination of options 3636 * @throws IOException 3637 * if an I/O error occurs writing to or creating the file, or the 3638 * text cannot be encoded using the specified charset 3639 * @throws UnsupportedOperationException 3640 * if an unsupported option is specified 3641 * @throws SecurityException 3642 * In the case of the default provider, and a security manager is 3643 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3644 * method is invoked to check write access to the file. The {@link 3645 * SecurityManager#checkDelete(String) checkDelete} method is 3646 * invoked to check delete access if the file is opened with the 3647 * {@code DELETE_ON_CLOSE} option. 3648 * 3649 * @since 11 3650 */ 3651 public static Path writeString(Path path, CharSequence csq, OpenOption... options) 3652 throws IOException 3653 { 3654 return writeString(path, csq, StandardCharsets.UTF_8, options); 3655 } 3656 3657 /** 3658 * Write a {@linkplain java.lang.CharSequence CharSequence} to a file. 3659 * Characters are encoded into bytes using the specified 3660 * {@linkplain java.nio.charset.Charset charset}. 3661 * 3662 * <p> All characters are written as they are, including the line separators in 3663 * the char sequence. No extra characters are added. 3664 * 3665 * <p> The {@code options} parameter specifies how the file is created 3666 * or opened. If no options are present then this method works as if the 3667 * {@link StandardOpenOption#CREATE CREATE}, {@link 3668 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link 3669 * StandardOpenOption#WRITE WRITE} options are present. In other words, it 3670 * opens the file for writing, creating the file if it doesn't exist, or 3671 * initially truncating an existing {@link #isRegularFile regular-file} to 3672 * a size of {@code 0}. 3673 * 3674 * 3675 * @param path 3676 * the path to the file 3677 * @param csq 3678 * the CharSequence to be written 3679 * @param cs 3680 * the charset to use for encoding 3681 * @param options 3682 * options specifying how the file is opened 3683 * 3684 * @return the path 3685 * 3686 * @throws IllegalArgumentException 3687 * if {@code options} contains an invalid combination of options 3688 * @throws IOException 3689 * if an I/O error occurs writing to or creating the file, or the 3690 * text cannot be encoded using the specified charset 3691 * @throws UnsupportedOperationException 3692 * if an unsupported option is specified 3693 * @throws SecurityException 3694 * In the case of the default provider, and a security manager is 3695 * installed, the {@link SecurityManager#checkWrite(String) checkWrite} 3696 * method is invoked to check write access to the file. The {@link 3697 * SecurityManager#checkDelete(String) checkDelete} method is 3698 * invoked to check delete access if the file is opened with the 3699 * {@code DELETE_ON_CLOSE} option. 3700 * 3701 * @since 11 3702 */ 3703 public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) 3704 throws IOException 3705 { 3706 // ensure the text is not null before opening file 3707 Objects.requireNonNull(path); 3708 Objects.requireNonNull(csq); 3709 Objects.requireNonNull(cs); 3710 3711 byte[] bytes = JLA.getBytesNoRepl(String.valueOf(csq), cs); 3712 write(path, bytes, options); 3713 3714 return path; 3715 } 3716 3717 // -- Stream APIs -- 3718 3719 /** 3720 * Return a lazily populated {@code Stream}, the elements of 3721 * which are the entries in the directory. The listing is not recursive. 3722 * 3723 * <p> The elements of the stream are {@link Path} objects that are 3724 * obtained as if by {@link Path#resolve(Path) resolving} the name of the 3725 * directory entry against {@code dir}. Some file systems maintain special 3726 * links to the directory itself and the directory's parent directory. 3727 * Entries representing these links are not included. 3728 * 3729 * <p> The stream is <i>weakly consistent</i>. It is thread safe but does 3730 * not freeze the directory while iterating, so it may (or may not) 3731 * reflect updates to the directory that occur after returning from this 3732 * method. 3733 * 3734 * <p> The returned stream contains a reference to an open directory. 3735 * The directory is closed by closing the stream. 3736 * 3737 * <p> Operating on a closed stream behaves as if the end of stream 3738 * has been reached. Due to read-ahead, one or more elements may be 3739 * returned after the stream has been closed. 3740 * 3741 * <p> If an {@link IOException} is thrown when accessing the directory 3742 * after this method has returned, it is wrapped in an {@link 3743 * UncheckedIOException} which will be thrown from the method that caused 3744 * the access to take place. 3745 * 3746 * @apiNote 3747 * This method must be used within a try-with-resources statement or similar 3748 * control structure to ensure that the stream's open directory is closed 3749 * promptly after the stream's operations have completed. 3750 * 3751 * @param dir The path to the directory 3752 * 3753 * @return The {@code Stream} describing the content of the 3754 * directory 3755 * 3756 * @throws NotDirectoryException 3757 * if the file could not otherwise be opened because it is not 3758 * a directory <i>(optional specific exception)</i> 3759 * @throws IOException 3760 * if an I/O error occurs when opening the directory 3761 * @throws SecurityException 3762 * In the case of the default provider, and a security manager is 3763 * installed, the {@link SecurityManager#checkRead(String) checkRead} 3764 * method is invoked to check read access to the directory. 3765 * 3766 * @see #newDirectoryStream(Path) 3767 * @since 1.8 3768 */ 3769 public static Stream<Path> list(Path dir) throws IOException { 3770 DirectoryStream<Path> ds = Files.newDirectoryStream(dir); 3771 try { 3772 final Iterator<Path> delegate = ds.iterator(); 3773 3774 // Re-wrap DirectoryIteratorException to UncheckedIOException 3775 Iterator<Path> iterator = new Iterator<>() { 3776 @Override 3777 public boolean hasNext() { 3778 try { 3779 return delegate.hasNext(); 3780 } catch (DirectoryIteratorException e) { 3781 throw new UncheckedIOException(e.getCause()); 3782 } 3783 } 3784 @Override 3785 public Path next() { 3786 try { 3787 return delegate.next(); 3788 } catch (DirectoryIteratorException e) { 3789 throw new UncheckedIOException(e.getCause()); 3790 } 3791 } 3792 }; 3793 3794 Spliterator<Path> spliterator = 3795 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT); 3796 return StreamSupport.stream(spliterator, false) 3797 .onClose(asUncheckedRunnable(ds)); 3798 } catch (Error|RuntimeException e) { 3799 try { 3800 ds.close(); 3801 } catch (IOException ex) { 3802 try { 3803 e.addSuppressed(ex); 3804 } catch (Throwable ignore) {} 3805 } 3806 throw e; 3807 } 3808 } 3809 3810 /** 3811 * Return a {@code Stream} that is lazily populated with {@code 3812 * Path} by walking the file tree rooted at a given starting file. The 3813 * file tree is traversed <em>depth-first</em>, the elements in the stream 3814 * are {@link Path} objects that are obtained as if by {@link 3815 * Path#resolve(Path) resolving} the relative path against {@code start}. 3816 * 3817 * <p> The {@code stream} walks the file tree as elements are consumed. 3818 * The {@code Stream} returned is guaranteed to have at least one 3819 * element, the starting file itself. For each file visited, the stream 3820 * attempts to read its {@link BasicFileAttributes}. If the file is a 3821 * directory and can be opened successfully, entries in the directory, and 3822 * their <em>descendants</em> will follow the directory in the stream as 3823 * they are encountered. When all entries have been visited, then the 3824 * directory is closed. The file tree walk then continues at the next 3825 * <em>sibling</em> of the directory. 3826 * 3827 * <p> The stream is <i>weakly consistent</i>. It does not freeze the 3828 * file tree while iterating, so it may (or may not) reflect updates to 3829 * the file tree that occur after returned from this method. 3830 * 3831 * <p> By default, symbolic links are not automatically followed by this 3832 * method. If the {@code options} parameter contains the {@link 3833 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are 3834 * followed. When following links, and the attributes of the target cannot 3835 * be read, then this method attempts to get the {@code BasicFileAttributes} 3836 * of the link. 3837 * 3838 * <p> If the {@code options} parameter contains the {@link 3839 * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then the stream keeps 3840 * track of directories visited so that cycles can be detected. A cycle 3841 * arises when there is an entry in a directory that is an ancestor of the 3842 * directory. Cycle detection is done by recording the {@link 3843 * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, 3844 * or if file keys are not available, by invoking the {@link #isSameFile 3845 * isSameFile} method to test if a directory is the same file as an 3846 * ancestor. When a cycle is detected it is treated as an I/O error with 3847 * an instance of {@link FileSystemLoopException}. 3848 * 3849 * <p> The {@code maxDepth} parameter is the maximum number of levels of 3850 * directories to visit. A value of {@code 0} means that only the starting 3851 * file is visited, unless denied by the security manager. A value of 3852 * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all 3853 * levels should be visited. 3854 * 3855 * <p> When a security manager is installed and it denies access to a file 3856 * (or directory), then it is ignored and not included in the stream. 3857 * 3858 * <p> The returned stream contains references to one or more open directories. 3859 * The directories are closed by closing the stream. 3860 * 3861 * <p> If an {@link IOException} is thrown when accessing the directory 3862 * after this method has returned, it is wrapped in an {@link 3863 * UncheckedIOException} which will be thrown from the method that caused 3864 * the access to take place. 3865 * 3866 * @apiNote 3867 * This method must be used within a try-with-resources statement or similar 3868 * control structure to ensure that the stream's open directories are closed 3869 * promptly after the stream's operations have completed. 3870 * 3871 * @param start 3872 * the starting file 3873 * @param maxDepth 3874 * the maximum number of directory levels to visit 3875 * @param options 3876 * options to configure the traversal 3877 * 3878 * @return the {@link Stream} of {@link Path} 3879 * 3880 * @throws IllegalArgumentException 3881 * if the {@code maxDepth} parameter is negative 3882 * @throws SecurityException 3883 * If the security manager denies access to the starting file. 3884 * In the case of the default provider, the {@link 3885 * SecurityManager#checkRead(String) checkRead} method is invoked 3886 * to check read access to the directory. 3887 * @throws IOException 3888 * if an I/O error is thrown when accessing the starting file. 3889 * @since 1.8 3890 */ 3891 public static Stream<Path> walk(Path start, 3892 int maxDepth, 3893 FileVisitOption... options) 3894 throws IOException 3895 { 3896 FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); 3897 try { 3898 Spliterator<FileTreeWalker.Event> spliterator = 3899 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT); 3900 return StreamSupport.stream(spliterator, false) 3901 .onClose(iterator::close) 3902 .map(entry -> entry.file()); 3903 } catch (Error|RuntimeException e) { 3904 iterator.close(); 3905 throw e; 3906 } 3907 } 3908 3909 /** 3910 * Return a {@code Stream} that is lazily populated with {@code 3911 * Path} by walking the file tree rooted at a given starting file. The 3912 * file tree is traversed <em>depth-first</em>, the elements in the stream 3913 * are {@link Path} objects that are obtained as if by {@link 3914 * Path#resolve(Path) resolving} the relative path against {@code start}. 3915 * 3916 * <p> This method works as if invoking it were equivalent to evaluating the 3917 * expression: 3918 * <blockquote><pre> 3919 * walk(start, Integer.MAX_VALUE, options) 3920 * </pre></blockquote> 3921 * In other words, it visits all levels of the file tree. 3922 * 3923 * <p> The returned stream contains references to one or more open directories. 3924 * The directories are closed by closing the stream. 3925 * 3926 * @apiNote 3927 * This method must be used within a try-with-resources statement or similar 3928 * control structure to ensure that the stream's open directories are closed 3929 * promptly after the stream's operations have completed. 3930 * 3931 * @param start 3932 * the starting file 3933 * @param options 3934 * options to configure the traversal 3935 * 3936 * @return the {@link Stream} of {@link Path} 3937 * 3938 * @throws SecurityException 3939 * If the security manager denies access to the starting file. 3940 * In the case of the default provider, the {@link 3941 * SecurityManager#checkRead(String) checkRead} method is invoked 3942 * to check read access to the directory. 3943 * @throws IOException 3944 * if an I/O error is thrown when accessing the starting file. 3945 * 3946 * @see #walk(Path, int, FileVisitOption...) 3947 * @since 1.8 3948 */ 3949 public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException { 3950 return walk(start, Integer.MAX_VALUE, options); 3951 } 3952 3953 /** 3954 * Return a {@code Stream} that is lazily populated with {@code 3955 * Path} by searching for files in a file tree rooted at a given starting 3956 * file. 3957 * 3958 * <p> This method walks the file tree in exactly the manner specified by 3959 * the {@link #walk walk} method. For each file encountered, the given 3960 * {@link BiPredicate} is invoked with its {@link Path} and {@link 3961 * BasicFileAttributes}. The {@code Path} object is obtained as if by 3962 * {@link Path#resolve(Path) resolving} the relative path against {@code 3963 * start} and is only included in the returned {@link Stream} if 3964 * the {@code BiPredicate} returns true. Compare to calling {@link 3965 * java.util.stream.Stream#filter filter} on the {@code Stream} 3966 * returned by {@code walk} method, this method may be more efficient by 3967 * avoiding redundant retrieval of the {@code BasicFileAttributes}. 3968 * 3969 * <p> The returned stream contains references to one or more open directories. 3970 * The directories are closed by closing the stream. 3971 * 3972 * <p> If an {@link IOException} is thrown when accessing the directory 3973 * after returned from this method, it is wrapped in an {@link 3974 * UncheckedIOException} which will be thrown from the method that caused 3975 * the access to take place. 3976 * 3977 * @apiNote 3978 * This method must be used within a try-with-resources statement or similar 3979 * control structure to ensure that the stream's open directories are closed 3980 * promptly after the stream's operations have completed. 3981 * 3982 * @param start 3983 * the starting file 3984 * @param maxDepth 3985 * the maximum number of directory levels to search 3986 * @param matcher 3987 * the function used to decide whether a file should be included 3988 * in the returned stream 3989 * @param options 3990 * options to configure the traversal 3991 * 3992 * @return the {@link Stream} of {@link Path} 3993 * 3994 * @throws IllegalArgumentException 3995 * if the {@code maxDepth} parameter is negative 3996 * @throws SecurityException 3997 * If the security manager denies access to the starting file. 3998 * In the case of the default provider, the {@link 3999 * SecurityManager#checkRead(String) checkRead} method is invoked 4000 * to check read access to the directory. 4001 * @throws IOException 4002 * if an I/O error is thrown when accessing the starting file. 4003 * 4004 * @see #walk(Path, int, FileVisitOption...) 4005 * @since 1.8 4006 */ 4007 public static Stream<Path> find(Path start, 4008 int maxDepth, 4009 BiPredicate<Path, BasicFileAttributes> matcher, 4010 FileVisitOption... options) 4011 throws IOException 4012 { 4013 FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); 4014 try { 4015 Spliterator<FileTreeWalker.Event> spliterator = 4016 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT); 4017 return StreamSupport.stream(spliterator, false) 4018 .onClose(iterator::close) 4019 .filter(entry -> matcher.test(entry.file(), entry.attributes())) 4020 .map(entry -> entry.file()); 4021 } catch (Error|RuntimeException e) { 4022 iterator.close(); 4023 throw e; 4024 } 4025 } 4026 4027 4028 /** 4029 * Read all lines from a file as a {@code Stream}. Unlike {@link 4030 * #readAllLines(Path, Charset) readAllLines}, this method does not read 4031 * all lines into a {@code List}, but instead populates lazily as the stream 4032 * is consumed. 4033 * 4034 * <p> Bytes from the file are decoded into characters using the specified 4035 * charset and the same line terminators as specified by {@code 4036 * readAllLines} are supported. 4037 * 4038 * <p> The returned stream contains a reference to an open file. The file 4039 * is closed by closing the stream. 4040 * 4041 * <p> The file contents should not be modified during the execution of the 4042 * terminal stream operation. Otherwise, the result of the terminal stream 4043 * operation is undefined. 4044 * 4045 * <p> After this method returns, then any subsequent I/O exception that 4046 * occurs while reading from the file or when a malformed or unmappable byte 4047 * sequence is read, is wrapped in an {@link UncheckedIOException} that will 4048 * be thrown from the 4049 * {@link java.util.stream.Stream} method that caused the read to take 4050 * place. In case an {@code IOException} is thrown when closing the file, 4051 * it is also wrapped as an {@code UncheckedIOException}. 4052 * 4053 * @apiNote 4054 * This method must be used within a try-with-resources statement or similar 4055 * control structure to ensure that the stream's open file is closed promptly 4056 * after the stream's operations have completed. 4057 * 4058 * @implNote 4059 * This implementation supports good parallel stream performance for the 4060 * standard charsets {@link StandardCharsets#UTF_8 UTF-8}, 4061 * {@link StandardCharsets#US_ASCII US-ASCII} and 4062 * {@link StandardCharsets#ISO_8859_1 ISO-8859-1}. Such 4063 * <em>line-optimal</em> charsets have the property that the encoded bytes 4064 * of a line feed ('\n') or a carriage return ('\r') are efficiently 4065 * identifiable from other encoded characters when randomly accessing the 4066 * bytes of the file. 4067 * 4068 * <p> For non-<em>line-optimal</em> charsets the stream source's 4069 * spliterator has poor splitting properties, similar to that of a 4070 * spliterator associated with an iterator or that associated with a stream 4071 * returned from {@link BufferedReader#lines()}. Poor splitting properties 4072 * can result in poor parallel stream performance. 4073 * 4074 * <p> For <em>line-optimal</em> charsets the stream source's spliterator 4075 * has good splitting properties, assuming the file contains a regular 4076 * sequence of lines. Good splitting properties can result in good parallel 4077 * stream performance. The spliterator for a <em>line-optimal</em> charset 4078 * takes advantage of the charset properties (a line feed or a carriage 4079 * return being efficient identifiable) such that when splitting it can 4080 * approximately divide the number of covered lines in half. 4081 * 4082 * @param path 4083 * the path to the file 4084 * @param cs 4085 * the charset to use for decoding 4086 * 4087 * @return the lines from the file as a {@code Stream} 4088 * 4089 * @throws IOException 4090 * if an I/O error occurs opening the file 4091 * @throws SecurityException 4092 * In the case of the default provider, and a security manager is 4093 * installed, the {@link SecurityManager#checkRead(String) checkRead} 4094 * method is invoked to check read access to the file. 4095 * 4096 * @see #readAllLines(Path, Charset) 4097 * @see #newBufferedReader(Path, Charset) 4098 * @see java.io.BufferedReader#lines() 4099 * @since 1.8 4100 */ 4101 public static Stream<String> lines(Path path, Charset cs) throws IOException { 4102 // Use the good splitting spliterator if: 4103 // 1) the path is associated with the default file system; 4104 // 2) the character set is supported; and 4105 // 3) the file size is such that all bytes can be indexed by int values 4106 // (this limitation is imposed by ByteBuffer) 4107 if (path.getFileSystem() == FileSystems.getDefault() && 4108 FileChannelLinesSpliterator.SUPPORTED_CHARSET_NAMES.contains(cs.name())) { 4109 FileChannel fc = FileChannel.open(path, StandardOpenOption.READ); 4110 4111 Stream<String> fcls = createFileChannelLinesStream(fc, cs); 4112 if (fcls != null) { 4113 return fcls; 4114 } 4115 fc.close(); 4116 } 4117 4118 return createBufferedReaderLinesStream(Files.newBufferedReader(path, cs)); 4119 } 4120 4121 private static Stream<String> createFileChannelLinesStream(FileChannel fc, Charset cs) throws IOException { 4122 try { 4123 // Obtaining the size from the FileChannel is much faster 4124 // than obtaining using path.toFile().length() 4125 long length = fc.size(); 4126 // FileChannel.size() may in certain circumstances return zero 4127 // for a non-zero length file so disallow this case. 4128 if (length > 0 && length <= Integer.MAX_VALUE) { 4129 Spliterator<String> s = new FileChannelLinesSpliterator(fc, cs, 0, (int) length); 4130 return StreamSupport.stream(s, false) 4131 .onClose(Files.asUncheckedRunnable(fc)); 4132 } 4133 } catch (Error|RuntimeException|IOException e) { 4134 try { 4135 fc.close(); 4136 } catch (IOException ex) { 4137 try { 4138 e.addSuppressed(ex); 4139 } catch (Throwable ignore) { 4140 } 4141 } 4142 throw e; 4143 } 4144 return null; 4145 } 4146 4147 private static Stream<String> createBufferedReaderLinesStream(BufferedReader br) { 4148 try { 4149 return br.lines().onClose(asUncheckedRunnable(br)); 4150 } catch (Error|RuntimeException e) { 4151 try { 4152 br.close(); 4153 } catch (IOException ex) { 4154 try { 4155 e.addSuppressed(ex); 4156 } catch (Throwable ignore) { 4157 } 4158 } 4159 throw e; 4160 } 4161 } 4162 4163 /** 4164 * Read all lines from a file as a {@code Stream}. Bytes from the file are 4165 * decoded into characters using the {@link StandardCharsets#UTF_8 UTF-8} 4166 * {@link Charset charset}. 4167 * 4168 * <p> The returned stream contains a reference to an open file. The file 4169 * is closed by closing the stream. 4170 * 4171 * <p> The file contents should not be modified during the execution of the 4172 * terminal stream operation. Otherwise, the result of the terminal stream 4173 * operation is undefined. 4174 * 4175 * <p> This method works as if invoking it were equivalent to evaluating the 4176 * expression: 4177 * <pre>{@code 4178 * Files.lines(path, StandardCharsets.UTF_8) 4179 * }</pre> 4180 * 4181 * @apiNote 4182 * This method must be used within a try-with-resources statement or similar 4183 * control structure to ensure that the stream's open file is closed promptly 4184 * after the stream's operations have completed. 4185 * 4186 * @param path 4187 * the path to the file 4188 * 4189 * @return the lines from the file as a {@code Stream} 4190 * 4191 * @throws IOException 4192 * if an I/O error occurs opening the file 4193 * @throws SecurityException 4194 * In the case of the default provider, and a security manager is 4195 * installed, the {@link SecurityManager#checkRead(String) checkRead} 4196 * method is invoked to check read access to the file. 4197 * 4198 * @since 1.8 4199 */ 4200 public static Stream<String> lines(Path path) throws IOException { 4201 return lines(path, StandardCharsets.UTF_8); 4202 } 4203 }