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