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