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