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