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