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