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