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