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