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