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