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