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