1 /*
   2  * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.file;
  27 
  28 import java.io.BufferedReader;
  29 import java.io.BufferedWriter;
  30 import java.io.Closeable;
  31 import java.io.File;
  32 import java.io.IOException;
  33 import java.io.InputStream;
  34 import java.io.InputStreamReader;
  35 import java.io.OutputStream;
  36 import java.io.OutputStreamWriter;
  37 import java.io.Reader;
  38 import java.io.UncheckedIOException;
  39 import java.io.Writer;
  40 import java.nio.channels.Channels;
  41 import java.nio.channels.FileChannel;
  42 import java.nio.channels.SeekableByteChannel;
  43 import java.nio.charset.Charset;
  44 import java.nio.charset.CharsetDecoder;
  45 import java.nio.charset.CharsetEncoder;
  46 import java.nio.charset.StandardCharsets;
  47 import java.nio.file.attribute.BasicFileAttributeView;
  48 import java.nio.file.attribute.BasicFileAttributes;
  49 import java.nio.file.attribute.DosFileAttributes;   // javadoc
  50 import java.nio.file.attribute.FileAttribute;
  51 import java.nio.file.attribute.FileAttributeView;
  52 import java.nio.file.attribute.FileOwnerAttributeView;
  53 import java.nio.file.attribute.FileStoreAttributeView;
  54 import java.nio.file.attribute.FileTime;
  55 import java.nio.file.attribute.PosixFileAttributeView;
  56 import java.nio.file.attribute.PosixFileAttributes;
  57 import java.nio.file.attribute.PosixFilePermission;
  58 import java.nio.file.attribute.UserPrincipal;
  59 import java.nio.file.spi.FileSystemProvider;
  60 import java.nio.file.spi.FileTypeDetector;
  61 import java.security.AccessController;
  62 import java.security.PrivilegedAction;
  63 import java.util.ArrayList;
  64 import java.util.Arrays;
  65 import java.util.Collections;
  66 import java.util.EnumSet;
  67 import java.util.HashSet;
  68 import java.util.Iterator;
  69 import java.util.List;
  70 import java.util.Map;
  71 import java.util.Objects;
  72 import java.util.ServiceLoader;
  73 import java.util.Set;
  74 import java.util.Spliterator;
  75 import java.util.Spliterators;
  76 import java.util.function.BiPredicate;

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



















































































































3574      * after this method has returned, it is wrapped in an {@link
3575      * UncheckedIOException} which will be thrown from the method that caused
3576      * the access to take place.
3577      *
3578      * @apiNote
3579      * This method must be used within a try-with-resources statement or similar
3580      * control structure to ensure that the stream's open directories are closed
3581      * promptly after the stream's operations have completed.
3582      *
3583      * @param   start
3584      *          the starting file
3585      * @param   maxDepth
3586      *          the maximum number of directory levels to visit
3587      * @param   options
3588      *          options to configure the traversal
3589      *
3590      * @return  the {@link Stream} of {@link Path}
3591      *
3592      * @throws  IllegalArgumentException
3593      *          if the {@code maxDepth} parameter is negative




3594      * @throws  SecurityException
3595      *          If the security manager denies access to the starting file.
3596      *          In the case of the default provider, the {@link
3597      *          SecurityManager#checkRead(String) checkRead} method is invoked
3598      *          to check read access to the directory.
3599      * @throws  IOException
3600      *          if an I/O error is thrown when accessing the starting file.
3601      * @since   1.8
3602      */
3603     public static Stream<Path> walk(Path start,
3604                                     int maxDepth,
3605                                     FileVisitOption... options)
3606         throws IOException
3607     {
3608         FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);
3609         try {
3610             Spliterator<FileTreeWalker.Event> spliterator =
3611                 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);
3612             return StreamSupport.stream(spliterator, false)
3613                                 .onClose(iterator::close)
3614                                 .map(entry -> entry.file());
3615         } catch (Error|RuntimeException e) {
3616             iterator.close();
3617             throw e;
3618         }
3619     }
3620 
3621     /**
3622      * Return a {@code Stream} that is lazily populated with {@code
3623      * Path} by walking the file tree rooted at a given starting file.  The
3624      * file tree is traversed <em>depth-first</em>, the elements in the stream
3625      * are {@link Path} objects that are obtained as if by {@link
3626      * Path#resolve(Path) resolving} the relative path against {@code start}.
3627      *
3628      * <p> This method works as if invoking it were equivalent to evaluating the
3629      * expression:
3630      * <blockquote><pre>
3631      * walk(start, Integer.MAX_VALUE, options)
3632      * </pre></blockquote>
3633      * In other words, it visits all levels of the file tree.
3634      *
3635      * <p> The returned stream contains references to one or more open directories.
3636      * The directories are closed by closing the stream.
3637      *
3638      * @apiNote
3639      * This method must be used within a try-with-resources statement or similar
3640      * control structure to ensure that the stream's open directories are closed
3641      * promptly after the stream's operations have completed.
3642      *
3643      * @param   start
3644      *          the starting file
3645      * @param   options
3646      *          options to configure the traversal
3647      *
3648      * @return  the {@link Stream} of {@link Path}
3649      *




3650      * @throws  SecurityException
3651      *          If the security manager denies access to the starting file.
3652      *          In the case of the default provider, the {@link
3653      *          SecurityManager#checkRead(String) checkRead} method is invoked
3654      *          to check read access to the directory.
3655      * @throws  IOException
3656      *          if an I/O error is thrown when accessing the starting file.
3657      *
3658      * @see     #walk(Path, int, FileVisitOption...)
3659      * @since   1.8
3660      */
3661     public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException {
3662         return walk(start, Integer.MAX_VALUE, options);
3663     }
3664 
3665     /**
3666      * Return a {@code Stream} that is lazily populated with {@code
3667      * Path} by searching for files in a file tree rooted at a given starting
3668      * file.
3669      *
3670      * <p> This method walks the file tree in exactly the manner specified by
3671      * the {@link #walk walk} method. For each file encountered, the given
3672      * {@link BiPredicate} is invoked with its {@link Path} and {@link
3673      * BasicFileAttributes}. The {@code Path} object is obtained as if by
3674      * {@link Path#resolve(Path) resolving} the relative path against {@code
3675      * start} and is only included in the returned {@link Stream} if
3676      * the {@code BiPredicate} returns true. Compare to calling {@link
3677      * java.util.stream.Stream#filter filter} on the {@code Stream}
3678      * returned by {@code walk} method, this method may be more efficient by
3679      * avoiding redundant retrieval of the {@code BasicFileAttributes}.
3680      *
3681      * <p> The returned stream contains references to one or more open directories.
3682      * The directories are closed by closing the stream.
3683      *
3684      * <p> If an {@link IOException} is thrown when accessing the directory

























































































3685      * after returned from this method, it is wrapped in an {@link
3686      * UncheckedIOException} which will be thrown from the method that caused
3687      * the access to take place.
3688      *
3689      * @apiNote
3690      * This method must be used within a try-with-resources statement or similar
3691      * control structure to ensure that the stream's open directories are closed
3692      * promptly after the stream's operations have completed.
3693      *
3694      * @param   start
3695      *          the starting file
3696      * @param   maxDepth
3697      *          the maximum number of directory levels to search
3698      * @param   matcher
3699      *          the function used to decide whether a file should be included
3700      *          in the returned stream
3701      * @param   options
3702      *          options to configure the traversal
3703      *
3704      * @return  the {@link Stream} of {@link Path}
3705      *
3706      * @throws  IllegalArgumentException
3707      *          if the {@code maxDepth} parameter is negative




3708      * @throws  SecurityException
3709      *          If the security manager denies access to the starting file.
3710      *          In the case of the default provider, the {@link
3711      *          SecurityManager#checkRead(String) checkRead} method is invoked
3712      *          to check read access to the directory.
3713      * @throws  IOException
3714      *          if an I/O error is thrown when accessing the starting file.
3715      *

3716      * @see     #walk(Path, int, FileVisitOption...)
3717      * @since   1.8
3718      */
3719     public static Stream<Path> find(Path start,
3720                                     int maxDepth,
3721                                     BiPredicate<Path, BasicFileAttributes> matcher,
3722                                     FileVisitOption... options)
3723         throws IOException
3724     {
3725         FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);
3726         try {
3727             Spliterator<FileTreeWalker.Event> spliterator =
3728                 Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);
3729             return StreamSupport.stream(spliterator, false)
3730                                 .onClose(iterator::close)
3731                                 .filter(entry -> matcher.test(entry.file(), entry.attributes()))
3732                                 .map(entry -> entry.file());
3733         } catch (Error|RuntimeException e) {
3734             iterator.close();
3735             throw e;
3736         }
3737     }
3738 
3739 
3740     /**
3741      * Read all lines from a file as a {@code Stream}. Unlike {@link
3742      * #readAllLines(Path, Charset) readAllLines}, this method does not read
3743      * all lines into a {@code List}, but instead populates lazily as the stream
3744      * is consumed.
3745      *
3746      * <p> Bytes from the file are decoded into characters using the specified
3747      * charset and the same line terminators as specified by {@code
3748      * readAllLines} are supported.
3749      *
3750      * <p> The returned stream contains a reference to an open file. The file
3751      * is closed by closing the stream.
3752      *
3753      * <p> The file contents should not be modified during the execution of the
3754      * terminal stream operation. Otherwise, the result of the terminal stream
3755      * operation is undefined.
3756      *
3757      * <p> After this method returns, then any subsequent I/O exception that
3758      * occurs while reading from the file or when a malformed or unmappable byte
3759      * sequence is read, is wrapped in an {@link UncheckedIOException} that will
3760      * be thrown from the
3761      * {@link java.util.stream.Stream} method that caused the read to take
3762      * place. In case an {@code IOException} is thrown when closing the file,
3763      * it is also wrapped as an {@code UncheckedIOException}.
3764      *
3765      * @apiNote
3766      * This method must be used within a try-with-resources statement or similar
3767      * control structure to ensure that the stream's open file is closed promptly
3768      * after the stream's operations have completed.
3769      *
3770      * @implNote
3771      * This implementation supports good parallel stream performance for the
3772      * standard charsets {@link StandardCharsets#UTF_8 UTF-8},
3773      * {@link StandardCharsets#US_ASCII US-ASCII} and
3774      * {@link StandardCharsets#ISO_8859_1 ISO-8859-1}.  Such
3775      * <em>line-optimal</em> charsets have the property that the encoded bytes
3776      * of a line feed ('\n') or a carriage return ('\r') are efficiently
3777      * identifiable from other encoded characters when randomly accessing the
3778      * bytes of the file.
3779      *
3780      * <p> For non-<em>line-optimal</em> charsets the stream source's
3781      * spliterator has poor splitting properties, similar to that of a
3782      * spliterator associated with an iterator or that associated with a stream
3783      * returned from {@link BufferedReader#lines()}.  Poor splitting properties
3784      * can result in poor parallel stream performance.
3785      *
3786      * <p> For <em>line-optimal</em> charsets the stream source's spliterator
3787      * has good splitting properties, assuming the file contains a regular
3788      * sequence of lines.  Good splitting properties can result in good parallel
3789      * stream performance.  The spliterator for a <em>line-optimal</em> charset
3790      * takes advantage of the charset properties (a line feed or a carriage
3791      * return being efficient identifiable) such that when splitting it can
3792      * approximately divide the number of covered lines in half.
3793      *
3794      * @param   path
3795      *          the path to the file
3796      * @param   cs
3797      *          the charset to use for decoding
3798      *
3799      * @return  the lines from the file as a {@code Stream}
3800      *
3801      * @throws  IOException
3802      *          if an I/O error occurs opening the file
3803      * @throws  SecurityException
3804      *          In the case of the default provider, and a security manager is
3805      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3806      *          method is invoked to check read access to the file.
3807      *
3808      * @see     #readAllLines(Path, Charset)
3809      * @see     #newBufferedReader(Path, Charset)
3810      * @see     java.io.BufferedReader#lines()
3811      * @since   1.8
3812      */
3813     public static Stream<String> lines(Path path, Charset cs) throws IOException {
3814         // Use the good splitting spliterator if:
3815         // 1) the path is associated with the default file system;
3816         // 2) the character set is supported; and
3817         // 3) the file size is such that all bytes can be indexed by int values
3818         //    (this limitation is imposed by ByteBuffer)
3819         if (path.getFileSystem() == FileSystems.getDefault() &&
3820             FileChannelLinesSpliterator.SUPPORTED_CHARSET_NAMES.contains(cs.name())) {
3821             FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);
3822 
3823             Stream<String> fcls = createFileChannelLinesStream(fc, cs);
3824             if (fcls != null) {
3825                 return fcls;
3826             }
3827             fc.close();
3828         }
3829 
3830         return createBufferedReaderLinesStream(Files.newBufferedReader(path, cs));
3831     }
3832 
3833     private static Stream<String> createFileChannelLinesStream(FileChannel fc, Charset cs) throws IOException {
3834         try {
3835             // Obtaining the size from the FileChannel is much faster
3836             // than obtaining using path.toFile().length()
3837             long length = fc.size();
3838             if (length <= Integer.MAX_VALUE) {
3839                 Spliterator<String> s = new FileChannelLinesSpliterator(fc, cs, 0, (int) length);
3840                 return StreamSupport.stream(s, false)
3841                         .onClose(Files.asUncheckedRunnable(fc));
3842             }
3843         } catch (Error|RuntimeException|IOException e) {
3844             try {
3845                 fc.close();
3846             } catch (IOException ex) {
3847                 try {
3848                     e.addSuppressed(ex);
3849                 } catch (Throwable ignore) {
3850                 }
3851             }
3852             throw e;
3853         }
3854         return null;
3855     }
3856 
3857     private static Stream<String> createBufferedReaderLinesStream(BufferedReader br) {
3858         try {
3859             return br.lines().onClose(asUncheckedRunnable(br));
3860         } catch (Error|RuntimeException e) {
3861             try {
3862                 br.close();
3863             } catch (IOException ex) {
3864                 try {
3865                     e.addSuppressed(ex);
3866                 } catch (Throwable ignore) {
3867                 }
3868             }
3869             throw e;
3870         }
3871     }
3872 
3873     /**
3874      * Read all lines from a file as a {@code Stream}. Bytes from the file are
3875      * decoded into characters using the {@link StandardCharsets#UTF_8 UTF-8}
3876      * {@link Charset charset}.
3877      *
3878      * <p> The returned stream contains a reference to an open file. The file
3879      * is closed by closing the stream.
3880      *
3881      * <p> The file contents should not be modified during the execution of the
3882      * terminal stream operation. Otherwise, the result of the terminal stream
3883      * operation is undefined.
3884      *
3885      * <p> This method works as if invoking it were equivalent to evaluating the
3886      * expression:
3887      * <pre>{@code
3888      * Files.lines(path, StandardCharsets.UTF_8)
3889      * }</pre>
3890      *
3891      * @apiNote
3892      * This method must be used within a try-with-resources statement or similar
3893      * control structure to ensure that the stream's open file is closed promptly
3894      * after the stream's operations have completed.
3895      *
3896      * @param   path
3897      *          the path to the file
3898      *
3899      * @return  the lines from the file as a {@code Stream}
3900      *
3901      * @throws  IOException
3902      *          if an I/O error occurs opening the file
3903      * @throws  SecurityException
3904      *          In the case of the default provider, and a security manager is
3905      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3906      *          method is invoked to check read access to the file.
3907      *
3908      * @since 1.8
3909      */
3910     public static Stream<String> lines(Path path) throws IOException {
3911         return lines(path, StandardCharsets.UTF_8);
3912     }
3913 }
--- EOF ---