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