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