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