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