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