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