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