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