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