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