Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/io/File.java
41152 views
1
/*
2
* Copyright (c) 1994, 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.io;
27
28
import java.net.URI;
29
import java.net.URL;
30
import java.net.MalformedURLException;
31
import java.net.URISyntaxException;
32
import java.nio.file.FileStore;
33
import java.nio.file.FileSystems;
34
import java.nio.file.Path;
35
import java.security.SecureRandom;
36
import java.util.ArrayList;
37
import java.util.List;
38
import sun.security.action.GetPropertyAction;
39
40
/**
41
* An abstract representation of file and directory pathnames.
42
*
43
* <p> User interfaces and operating systems use system-dependent <em>pathname
44
* strings</em> to name files and directories. This class presents an
45
* abstract, system-independent view of hierarchical pathnames. An
46
* <em>abstract pathname</em> has two components:
47
*
48
* <ol>
49
* <li> An optional system-dependent <em>prefix</em> string,
50
* such as a disk-drive specifier, {@code "/"}&nbsp;for the UNIX root
51
* directory, or {@code "\\\\"}&nbsp;for a Microsoft Windows UNC pathname, and
52
* <li> A sequence of zero or more string <em>names</em>.
53
* </ol>
54
*
55
* The first name in an abstract pathname may be a directory name or, in the
56
* case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name
57
* in an abstract pathname denotes a directory; the last name may denote
58
* either a directory or a file. The <em>empty</em> abstract pathname has no
59
* prefix and an empty name sequence.
60
*
61
* <p> The conversion of a pathname string to or from an abstract pathname is
62
* inherently system-dependent. When an abstract pathname is converted into a
63
* pathname string, each name is separated from the next by a single copy of
64
* the default <em>separator character</em>. The default name-separator
65
* character is defined by the system property {@code file.separator}, and
66
* is made available in the public static fields {@link
67
* #separator} and {@link #separatorChar} of this class.
68
* When a pathname string is converted into an abstract pathname, the names
69
* within it may be separated by the default name-separator character or by any
70
* other name-separator character that is supported by the underlying system.
71
*
72
* <p> A pathname, whether abstract or in string form, may be either
73
* <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in
74
* that no other information is required in order to locate the file that it
75
* denotes. A relative pathname, in contrast, must be interpreted in terms of
76
* information taken from some other pathname. By default the classes in the
77
* {@code java.io} package always resolve relative pathnames against the
78
* current user directory. This directory is named by the system property
79
* {@code user.dir}, and is typically the directory in which the Java
80
* virtual machine was invoked.
81
*
82
* <p> The <em>parent</em> of an abstract pathname may be obtained by invoking
83
* the {@link #getParent} method of this class and consists of the pathname's
84
* prefix and each name in the pathname's name sequence except for the last.
85
* Each directory's absolute pathname is an ancestor of any {@code File}
86
* object with an absolute abstract pathname which begins with the directory's
87
* absolute pathname. For example, the directory denoted by the abstract
88
* pathname {@code "/usr"} is an ancestor of the directory denoted by the
89
* pathname {@code "/usr/local/bin"}.
90
*
91
* <p> The prefix concept is used to handle root directories on UNIX platforms,
92
* and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms,
93
* as follows:
94
*
95
* <ul>
96
*
97
* <li> For UNIX platforms, the prefix of an absolute pathname is always
98
* {@code "/"}. Relative pathnames have no prefix. The abstract pathname
99
* denoting the root directory has the prefix {@code "/"} and an empty
100
* name sequence.
101
*
102
* <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive
103
* specifier consists of the drive letter followed by {@code ":"} and
104
* possibly followed by {@code "\\"} if the pathname is absolute. The
105
* prefix of a UNC pathname is {@code "\\\\"}; the hostname and the share
106
* name are the first two names in the name sequence. A relative pathname that
107
* does not specify a drive has no prefix.
108
*
109
* </ul>
110
*
111
* <p> Instances of this class may or may not denote an actual file-system
112
* object such as a file or a directory. If it does denote such an object
113
* then that object resides in a <i>partition</i>. A partition is an
114
* operating system-specific portion of storage for a file system. A single
115
* storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may
116
* contain multiple partitions. The object, if any, will reside on the
117
* partition <a id="partName">named</a> by some ancestor of the absolute
118
* form of this pathname.
119
*
120
* <p> A file system may implement restrictions to certain operations on the
121
* actual file-system object, such as reading, writing, and executing. These
122
* restrictions are collectively known as <i>access permissions</i>. The file
123
* system may have multiple sets of access permissions on a single object.
124
* For example, one set may apply to the object's <i>owner</i>, and another
125
* may apply to all other users. The access permissions on an object may
126
* cause some methods in this class to fail.
127
*
128
* <p> Instances of the {@code File} class are immutable; that is, once
129
* created, the abstract pathname represented by a {@code File} object
130
* will never change.
131
*
132
* <h2>Interoperability with {@code java.nio.file} package</h2>
133
*
134
* <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>
135
* package defines interfaces and classes for the Java virtual machine to access
136
* files, file attributes, and file systems. This API may be used to overcome
137
* many of the limitations of the {@code java.io.File} class.
138
* The {@link #toPath toPath} method may be used to obtain a {@link
139
* Path} that uses the abstract path represented by a {@code File} object to
140
* locate a file. The resulting {@code Path} may be used with the {@link
141
* java.nio.file.Files} class to provide more efficient and extensive access to
142
* additional file operations, file attributes, and I/O exceptions to help
143
* diagnose errors when an operation on a file fails.
144
*
145
* @since 1.0
146
*/
147
148
public class File
149
implements Serializable, Comparable<File>
150
{
151
152
/**
153
* The FileSystem object representing the platform's local file system.
154
*/
155
private static final FileSystem fs = DefaultFileSystem.getFileSystem();
156
157
/**
158
* This abstract pathname's normalized pathname string. A normalized
159
* pathname string uses the default name-separator character and does not
160
* contain any duplicate or redundant separators.
161
*
162
* @serial
163
*/
164
private final String path;
165
166
/**
167
* Enum type that indicates the status of a file path.
168
*/
169
private static enum PathStatus { INVALID, CHECKED };
170
171
/**
172
* The flag indicating whether the file path is invalid.
173
*/
174
private transient PathStatus status = null;
175
176
/**
177
* Check if the file has an invalid path. Currently, the inspection of
178
* a file path is very limited, and it only covers Nul character check.
179
* Returning true means the path is definitely invalid/garbage. But
180
* returning false does not guarantee that the path is valid.
181
*
182
* @return true if the file path is invalid.
183
*/
184
final boolean isInvalid() {
185
PathStatus s = status;
186
if (s == null) {
187
s = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
188
: PathStatus.INVALID;
189
status = s;
190
}
191
return s == PathStatus.INVALID;
192
}
193
194
/**
195
* The length of this abstract pathname's prefix, or zero if it has no
196
* prefix.
197
*/
198
private final transient int prefixLength;
199
200
/**
201
* Returns the length of this abstract pathname's prefix.
202
* For use by FileSystem classes.
203
*/
204
int getPrefixLength() {
205
return prefixLength;
206
}
207
208
/**
209
* The system-dependent default name-separator character. This field is
210
* initialized to contain the first character of the value of the system
211
* property {@code file.separator}. On UNIX systems the value of this
212
* field is {@code '/'}; on Microsoft Windows systems it is {@code '\\'}.
213
*
214
* @see java.lang.System#getProperty(java.lang.String)
215
*/
216
public static final char separatorChar = fs.getSeparator();
217
218
/**
219
* The system-dependent default name-separator character, represented as a
220
* string for convenience. This string contains a single character, namely
221
* {@link #separatorChar}.
222
*/
223
public static final String separator = "" + separatorChar;
224
225
/**
226
* The system-dependent path-separator character. This field is
227
* initialized to contain the first character of the value of the system
228
* property {@code path.separator}. This character is used to
229
* separate filenames in a sequence of files given as a <em>path list</em>.
230
* On UNIX systems, this character is {@code ':'}; on Microsoft Windows systems it
231
* is {@code ';'}.
232
*
233
* @see java.lang.System#getProperty(java.lang.String)
234
*/
235
public static final char pathSeparatorChar = fs.getPathSeparator();
236
237
/**
238
* The system-dependent path-separator character, represented as a string
239
* for convenience. This string contains a single character, namely
240
* {@link #pathSeparatorChar}.
241
*/
242
public static final String pathSeparator = "" + pathSeparatorChar;
243
244
245
/* -- Constructors -- */
246
247
/**
248
* Internal constructor for already-normalized pathname strings.
249
*/
250
private File(String pathname, int prefixLength) {
251
this.path = pathname;
252
this.prefixLength = prefixLength;
253
}
254
255
/**
256
* Internal constructor for already-normalized pathname strings.
257
* The parameter order is used to disambiguate this method from the
258
* public(File, String) constructor.
259
*/
260
private File(String child, File parent) {
261
assert parent.path != null;
262
assert (!parent.path.isEmpty());
263
this.path = fs.resolve(parent.path, child);
264
this.prefixLength = parent.prefixLength;
265
}
266
267
/**
268
* Creates a new {@code File} instance by converting the given
269
* pathname string into an abstract pathname. If the given string is
270
* the empty string, then the result is the empty abstract pathname.
271
*
272
* @param pathname A pathname string
273
* @throws NullPointerException
274
* If the {@code pathname} argument is {@code null}
275
*/
276
public File(String pathname) {
277
if (pathname == null) {
278
throw new NullPointerException();
279
}
280
this.path = fs.normalize(pathname);
281
this.prefixLength = fs.prefixLength(this.path);
282
}
283
284
/* Note: The two-argument File constructors do not interpret an empty
285
parent abstract pathname as the current user directory. An empty parent
286
instead causes the child to be resolved against the system-dependent
287
directory defined by the FileSystem.getDefaultParent method. On Unix
288
this default is "/", while on Microsoft Windows it is "\\". This is required for
289
compatibility with the original behavior of this class. */
290
291
/**
292
* Creates a new {@code File} instance from a parent pathname string
293
* and a child pathname string.
294
*
295
* <p> If {@code parent} is {@code null} then the new
296
* {@code File} instance is created as if by invoking the
297
* single-argument {@code File} constructor on the given
298
* {@code child} pathname string.
299
*
300
* <p> Otherwise the {@code parent} pathname string is taken to denote
301
* a directory, and the {@code child} pathname string is taken to
302
* denote either a directory or a file. If the {@code child} pathname
303
* string is absolute then it is converted into a relative pathname in a
304
* system-dependent way. If {@code parent} is the empty string then
305
* the new {@code File} instance is created by converting
306
* {@code child} into an abstract pathname and resolving the result
307
* against a system-dependent default directory. Otherwise each pathname
308
* string is converted into an abstract pathname and the child abstract
309
* pathname is resolved against the parent.
310
*
311
* @param parent The parent pathname string
312
* @param child The child pathname string
313
* @throws NullPointerException
314
* If {@code child} is {@code null}
315
*/
316
public File(String parent, String child) {
317
if (child == null) {
318
throw new NullPointerException();
319
}
320
if (parent != null) {
321
if (parent.isEmpty()) {
322
this.path = fs.resolve(fs.getDefaultParent(),
323
fs.normalize(child));
324
} else {
325
this.path = fs.resolve(fs.normalize(parent),
326
fs.normalize(child));
327
}
328
} else {
329
this.path = fs.normalize(child);
330
}
331
this.prefixLength = fs.prefixLength(this.path);
332
}
333
334
/**
335
* Creates a new {@code File} instance from a parent abstract
336
* pathname and a child pathname string.
337
*
338
* <p> If {@code parent} is {@code null} then the new
339
* {@code File} instance is created as if by invoking the
340
* single-argument {@code File} constructor on the given
341
* {@code child} pathname string.
342
*
343
* <p> Otherwise the {@code parent} abstract pathname is taken to
344
* denote a directory, and the {@code child} pathname string is taken
345
* to denote either a directory or a file. If the {@code child}
346
* pathname string is absolute then it is converted into a relative
347
* pathname in a system-dependent way. If {@code parent} is the empty
348
* abstract pathname then the new {@code File} instance is created by
349
* converting {@code child} into an abstract pathname and resolving
350
* the result against a system-dependent default directory. Otherwise each
351
* pathname string is converted into an abstract pathname and the child
352
* abstract pathname is resolved against the parent.
353
*
354
* @param parent The parent abstract pathname
355
* @param child The child pathname string
356
* @throws NullPointerException
357
* If {@code child} is {@code null}
358
*/
359
public File(File parent, String child) {
360
if (child == null) {
361
throw new NullPointerException();
362
}
363
if (parent != null) {
364
if (parent.path.isEmpty()) {
365
this.path = fs.resolve(fs.getDefaultParent(),
366
fs.normalize(child));
367
} else {
368
this.path = fs.resolve(parent.path,
369
fs.normalize(child));
370
}
371
} else {
372
this.path = fs.normalize(child);
373
}
374
this.prefixLength = fs.prefixLength(this.path);
375
}
376
377
/**
378
* Creates a new {@code File} instance by converting the given
379
* {@code file:} URI into an abstract pathname.
380
*
381
* <p> The exact form of a {@code file:} URI is system-dependent, hence
382
* the transformation performed by this constructor is also
383
* system-dependent.
384
*
385
* <p> For a given abstract pathname <i>f</i> it is guaranteed that
386
*
387
* <blockquote><code>
388
* new File(</code><i>&nbsp;f</i><code>.{@link #toURI()
389
* toURI}()).equals(</code><i>&nbsp;f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}())
390
* </code></blockquote>
391
*
392
* so long as the original abstract pathname, the URI, and the new abstract
393
* pathname are all created in (possibly different invocations of) the same
394
* Java virtual machine. This relationship typically does not hold,
395
* however, when a {@code file:} URI that is created in a virtual machine
396
* on one operating system is converted into an abstract pathname in a
397
* virtual machine on a different operating system.
398
*
399
* @param uri
400
* An absolute, hierarchical URI with a scheme equal to
401
* {@code "file"}, a non-empty path component, and undefined
402
* authority, query, and fragment components
403
*
404
* @throws NullPointerException
405
* If {@code uri} is {@code null}
406
*
407
* @throws IllegalArgumentException
408
* If the preconditions on the parameter do not hold
409
*
410
* @see #toURI()
411
* @see java.net.URI
412
* @since 1.4
413
*/
414
public File(URI uri) {
415
416
// Check our many preconditions
417
if (!uri.isAbsolute())
418
throw new IllegalArgumentException("URI is not absolute");
419
if (uri.isOpaque())
420
throw new IllegalArgumentException("URI is not hierarchical");
421
String scheme = uri.getScheme();
422
if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
423
throw new IllegalArgumentException("URI scheme is not \"file\"");
424
if (uri.getRawAuthority() != null)
425
throw new IllegalArgumentException("URI has an authority component");
426
if (uri.getRawFragment() != null)
427
throw new IllegalArgumentException("URI has a fragment component");
428
if (uri.getRawQuery() != null)
429
throw new IllegalArgumentException("URI has a query component");
430
String p = uri.getPath();
431
if (p.isEmpty())
432
throw new IllegalArgumentException("URI path component is empty");
433
434
// Okay, now initialize
435
p = fs.fromURIPath(p);
436
if (File.separatorChar != '/')
437
p = p.replace('/', File.separatorChar);
438
this.path = fs.normalize(p);
439
this.prefixLength = fs.prefixLength(this.path);
440
}
441
442
443
/* -- Path-component accessors -- */
444
445
/**
446
* Returns the name of the file or directory denoted by this abstract
447
* pathname. This is just the last name in the pathname's name
448
* sequence. If the pathname's name sequence is empty, then the empty
449
* string is returned.
450
*
451
* @return The name of the file or directory denoted by this abstract
452
* pathname, or the empty string if this pathname's name sequence
453
* is empty
454
*/
455
public String getName() {
456
int index = path.lastIndexOf(separatorChar);
457
if (index < prefixLength) return path.substring(prefixLength);
458
return path.substring(index + 1);
459
}
460
461
/**
462
* Returns the pathname string of this abstract pathname's parent, or
463
* {@code null} if this pathname does not name a parent directory.
464
*
465
* <p> The <em>parent</em> of an abstract pathname consists of the
466
* pathname's prefix, if any, and each name in the pathname's name
467
* sequence except for the last. If the name sequence is empty then
468
* the pathname does not name a parent directory.
469
*
470
* @return The pathname string of the parent directory named by this
471
* abstract pathname, or {@code null} if this pathname
472
* does not name a parent
473
*/
474
public String getParent() {
475
int index = path.lastIndexOf(separatorChar);
476
if (index < prefixLength) {
477
if ((prefixLength > 0) && (path.length() > prefixLength))
478
return path.substring(0, prefixLength);
479
return null;
480
}
481
return path.substring(0, index);
482
}
483
484
/**
485
* Returns the abstract pathname of this abstract pathname's parent,
486
* or {@code null} if this pathname does not name a parent
487
* directory.
488
*
489
* <p> The <em>parent</em> of an abstract pathname consists of the
490
* pathname's prefix, if any, and each name in the pathname's name
491
* sequence except for the last. If the name sequence is empty then
492
* the pathname does not name a parent directory.
493
*
494
* @return The abstract pathname of the parent directory named by this
495
* abstract pathname, or {@code null} if this pathname
496
* does not name a parent
497
*
498
* @since 1.2
499
*/
500
public File getParentFile() {
501
String p = this.getParent();
502
if (p == null) return null;
503
if (getClass() != File.class) {
504
p = fs.normalize(p);
505
}
506
return new File(p, this.prefixLength);
507
}
508
509
/**
510
* Converts this abstract pathname into a pathname string. The resulting
511
* string uses the {@link #separator default name-separator character} to
512
* separate the names in the name sequence.
513
*
514
* @return The string form of this abstract pathname
515
*/
516
public String getPath() {
517
return path;
518
}
519
520
521
/* -- Path operations -- */
522
523
/**
524
* Tests whether this abstract pathname is absolute. The definition of
525
* absolute pathname is system dependent. On UNIX systems, a pathname is
526
* absolute if its prefix is {@code "/"}. On Microsoft Windows systems, a
527
* pathname is absolute if its prefix is a drive specifier followed by
528
* {@code "\\"}, or if its prefix is {@code "\\\\"}.
529
*
530
* @return {@code true} if this abstract pathname is absolute,
531
* {@code false} otherwise
532
*/
533
public boolean isAbsolute() {
534
return fs.isAbsolute(this);
535
}
536
537
/**
538
* Returns the absolute pathname string of this abstract pathname.
539
*
540
* <p> If this abstract pathname is already absolute, then the pathname
541
* string is simply returned as if by the {@link #getPath}
542
* method. If this abstract pathname is the empty abstract pathname then
543
* the pathname string of the current user directory, which is named by the
544
* system property {@code user.dir}, is returned. Otherwise this
545
* pathname is resolved in a system-dependent way. On UNIX systems, a
546
* relative pathname is made absolute by resolving it against the current
547
* user directory. On Microsoft Windows systems, a relative pathname is made absolute
548
* by resolving it against the current directory of the drive named by the
549
* pathname, if any; if not, it is resolved against the current user
550
* directory.
551
*
552
* @return The absolute pathname string denoting the same file or
553
* directory as this abstract pathname
554
*
555
* @throws SecurityException
556
* If a required system property value cannot be accessed.
557
*
558
* @see java.io.File#isAbsolute()
559
*/
560
public String getAbsolutePath() {
561
return fs.resolve(this);
562
}
563
564
/**
565
* Returns the absolute form of this abstract pathname. Equivalent to
566
* <code>new&nbsp;File(this.{@link #getAbsolutePath})</code>.
567
*
568
* @return The absolute abstract pathname denoting the same file or
569
* directory as this abstract pathname
570
*
571
* @throws SecurityException
572
* If a required system property value cannot be accessed.
573
*
574
* @since 1.2
575
*/
576
public File getAbsoluteFile() {
577
String absPath = getAbsolutePath();
578
if (getClass() != File.class) {
579
absPath = fs.normalize(absPath);
580
}
581
return new File(absPath, fs.prefixLength(absPath));
582
}
583
584
/**
585
* Returns the canonical pathname string of this abstract pathname.
586
*
587
* <p> A canonical pathname is both absolute and unique. The precise
588
* definition of canonical form is system-dependent. This method first
589
* converts this pathname to absolute form if necessary, as if by invoking the
590
* {@link #getAbsolutePath} method, and then maps it to its unique form in a
591
* system-dependent way. This typically involves removing redundant names
592
* such as {@code "."} and {@code ".."} from the pathname, resolving
593
* symbolic links (on UNIX platforms), and converting drive letters to a
594
* standard case (on Microsoft Windows platforms).
595
*
596
* <p> Every pathname that denotes an existing file or directory has a
597
* unique canonical form. Every pathname that denotes a nonexistent file
598
* or directory also has a unique canonical form. The canonical form of
599
* the pathname of a nonexistent file or directory may be different from
600
* the canonical form of the same pathname after the file or directory is
601
* created. Similarly, the canonical form of the pathname of an existing
602
* file or directory may be different from the canonical form of the same
603
* pathname after the file or directory is deleted.
604
*
605
* @return The canonical pathname string denoting the same file or
606
* directory as this abstract pathname
607
*
608
* @throws IOException
609
* If an I/O error occurs, which is possible because the
610
* construction of the canonical pathname may require
611
* filesystem queries
612
*
613
* @throws SecurityException
614
* If a required system property value cannot be accessed, or
615
* if a security manager exists and its {@link
616
* java.lang.SecurityManager#checkRead} method denies
617
* read access to the file
618
*
619
* @since 1.1
620
* @see Path#toRealPath
621
*/
622
public String getCanonicalPath() throws IOException {
623
if (isInvalid()) {
624
throw new IOException("Invalid file path");
625
}
626
return fs.canonicalize(fs.resolve(this));
627
}
628
629
/**
630
* Returns the canonical form of this abstract pathname. Equivalent to
631
* <code>new&nbsp;File(this.{@link #getCanonicalPath})</code>.
632
*
633
* @return The canonical pathname string denoting the same file or
634
* directory as this abstract pathname
635
*
636
* @throws IOException
637
* If an I/O error occurs, which is possible because the
638
* construction of the canonical pathname may require
639
* filesystem queries
640
*
641
* @throws SecurityException
642
* If a required system property value cannot be accessed, or
643
* if a security manager exists and its {@link
644
* java.lang.SecurityManager#checkRead} method denies
645
* read access to the file
646
*
647
* @since 1.2
648
* @see Path#toRealPath
649
*/
650
public File getCanonicalFile() throws IOException {
651
String canonPath = getCanonicalPath();
652
if (getClass() != File.class) {
653
canonPath = fs.normalize(canonPath);
654
}
655
return new File(canonPath, fs.prefixLength(canonPath));
656
}
657
658
private static String slashify(String path, boolean isDirectory) {
659
String p = path;
660
if (File.separatorChar != '/')
661
p = p.replace(File.separatorChar, '/');
662
if (!p.startsWith("/"))
663
p = "/" + p;
664
if (!p.endsWith("/") && isDirectory)
665
p = p + "/";
666
return p;
667
}
668
669
/**
670
* Converts this abstract pathname into a {@code file:} URL. The
671
* exact form of the URL is system-dependent. If it can be determined that
672
* the file denoted by this abstract pathname is a directory, then the
673
* resulting URL will end with a slash.
674
*
675
* @return A URL object representing the equivalent file URL
676
*
677
* @throws MalformedURLException
678
* If the path cannot be parsed as a URL
679
*
680
* @see #toURI()
681
* @see java.net.URI
682
* @see java.net.URI#toURL()
683
* @see java.net.URL
684
* @since 1.2
685
*
686
* @deprecated This method does not automatically escape characters that
687
* are illegal in URLs. It is recommended that new code convert an
688
* abstract pathname into a URL by first converting it into a URI, via the
689
* {@link #toURI() toURI} method, and then converting the URI into a URL
690
* via the {@link java.net.URI#toURL() URI.toURL} method.
691
*/
692
@Deprecated
693
public URL toURL() throws MalformedURLException {
694
if (isInvalid()) {
695
throw new MalformedURLException("Invalid file path");
696
}
697
return new URL("file", "", slashify(getAbsolutePath(), isDirectory()));
698
}
699
700
/**
701
* Constructs a {@code file:} URI that represents this abstract pathname.
702
*
703
* <p> The exact form of the URI is system-dependent. If it can be
704
* determined that the file denoted by this abstract pathname is a
705
* directory, then the resulting URI will end with a slash.
706
*
707
* <p> For a given abstract pathname <i>f</i>, it is guaranteed that
708
*
709
* <blockquote><code>
710
* new {@link #File(java.net.URI) File}(</code><i>&nbsp;f</i><code>.toURI()).equals(
711
* </code><i>&nbsp;f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}())
712
* </code></blockquote>
713
*
714
* so long as the original abstract pathname, the URI, and the new abstract
715
* pathname are all created in (possibly different invocations of) the same
716
* Java virtual machine. Due to the system-dependent nature of abstract
717
* pathnames, however, this relationship typically does not hold when a
718
* {@code file:} URI that is created in a virtual machine on one operating
719
* system is converted into an abstract pathname in a virtual machine on a
720
* different operating system.
721
*
722
* <p> Note that when this abstract pathname represents a UNC pathname then
723
* all components of the UNC (including the server name component) are encoded
724
* in the {@code URI} path. The authority component is undefined, meaning
725
* that it is represented as {@code null}. The {@link Path} class defines the
726
* {@link Path#toUri toUri} method to encode the server name in the authority
727
* component of the resulting {@code URI}. The {@link #toPath toPath} method
728
* may be used to obtain a {@code Path} representing this abstract pathname.
729
*
730
* @return An absolute, hierarchical URI with a scheme equal to
731
* {@code "file"}, a path representing this abstract pathname,
732
* and undefined authority, query, and fragment components
733
* @throws SecurityException If a required system property value cannot
734
* be accessed.
735
*
736
* @see #File(java.net.URI)
737
* @see java.net.URI
738
* @see java.net.URI#toURL()
739
* @since 1.4
740
*/
741
public URI toURI() {
742
try {
743
File f = getAbsoluteFile();
744
String sp = slashify(f.getPath(), f.isDirectory());
745
if (sp.startsWith("//"))
746
sp = "//" + sp;
747
return new URI("file", null, sp, null);
748
} catch (URISyntaxException x) {
749
throw new Error(x); // Can't happen
750
}
751
}
752
753
754
/* -- Attribute accessors -- */
755
756
/**
757
* Tests whether the application can read the file denoted by this
758
* abstract pathname. On some platforms it may be possible to start the
759
* Java virtual machine with special privileges that allow it to read
760
* files that are marked as unreadable. Consequently this method may return
761
* {@code true} even though the file does not have read permissions.
762
*
763
* @return {@code true} if and only if the file specified by this
764
* abstract pathname exists <em>and</em> can be read by the
765
* application; {@code false} otherwise
766
*
767
* @throws SecurityException
768
* If a security manager exists and its {@link
769
* java.lang.SecurityManager#checkRead(java.lang.String)}
770
* method denies read access to the file
771
*/
772
public boolean canRead() {
773
@SuppressWarnings("removal")
774
SecurityManager security = System.getSecurityManager();
775
if (security != null) {
776
security.checkRead(path);
777
}
778
if (isInvalid()) {
779
return false;
780
}
781
return fs.checkAccess(this, FileSystem.ACCESS_READ);
782
}
783
784
/**
785
* Tests whether the application can modify the file denoted by this
786
* abstract pathname. On some platforms it may be possible to start the
787
* Java virtual machine with special privileges that allow it to modify
788
* files that are marked read-only. Consequently this method may return
789
* {@code true} even though the file is marked read-only.
790
*
791
* @return {@code true} if and only if the file system actually
792
* contains a file denoted by this abstract pathname <em>and</em>
793
* the application is allowed to write to the file;
794
* {@code false} otherwise.
795
*
796
* @throws SecurityException
797
* If a security manager exists and its {@link
798
* java.lang.SecurityManager#checkWrite(java.lang.String)}
799
* method denies write access to the file
800
*/
801
public boolean canWrite() {
802
@SuppressWarnings("removal")
803
SecurityManager security = System.getSecurityManager();
804
if (security != null) {
805
security.checkWrite(path);
806
}
807
if (isInvalid()) {
808
return false;
809
}
810
return fs.checkAccess(this, FileSystem.ACCESS_WRITE);
811
}
812
813
/**
814
* Tests whether the file or directory denoted by this abstract pathname
815
* exists.
816
*
817
* @return {@code true} if and only if the file or directory denoted
818
* by this abstract pathname exists; {@code false} otherwise
819
*
820
* @throws SecurityException
821
* If a security manager exists and its {@link
822
* java.lang.SecurityManager#checkRead(java.lang.String)}
823
* method denies read access to the file or directory
824
*/
825
public boolean exists() {
826
@SuppressWarnings("removal")
827
SecurityManager security = System.getSecurityManager();
828
if (security != null) {
829
security.checkRead(path);
830
}
831
if (isInvalid()) {
832
return false;
833
}
834
return fs.hasBooleanAttributes(this, FileSystem.BA_EXISTS);
835
}
836
837
/**
838
* Tests whether the file denoted by this abstract pathname is a
839
* directory.
840
*
841
* <p> Where it is required to distinguish an I/O exception from the case
842
* that the file is not a directory, or where several attributes of the
843
* same file are required at the same time, then the {@link
844
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
845
* Files.readAttributes} method may be used.
846
*
847
* @return {@code true} if and only if the file denoted by this
848
* abstract pathname exists <em>and</em> is a directory;
849
* {@code false} otherwise
850
*
851
* @throws SecurityException
852
* If a security manager exists and its {@link
853
* java.lang.SecurityManager#checkRead(java.lang.String)}
854
* method denies read access to the file
855
*/
856
public boolean isDirectory() {
857
@SuppressWarnings("removal")
858
SecurityManager security = System.getSecurityManager();
859
if (security != null) {
860
security.checkRead(path);
861
}
862
if (isInvalid()) {
863
return false;
864
}
865
return fs.hasBooleanAttributes(this, FileSystem.BA_DIRECTORY);
866
}
867
868
/**
869
* Tests whether the file denoted by this abstract pathname is a normal
870
* file. A file is <em>normal</em> if it is not a directory and, in
871
* addition, satisfies other system-dependent criteria. Any non-directory
872
* file created by a Java application is guaranteed to be a normal file.
873
*
874
* <p> Where it is required to distinguish an I/O exception from the case
875
* that the file is not a normal file, or where several attributes of the
876
* same file are required at the same time, then the {@link
877
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
878
* Files.readAttributes} method may be used.
879
*
880
* @return {@code true} if and only if the file denoted by this
881
* abstract pathname exists <em>and</em> is a normal file;
882
* {@code false} otherwise
883
*
884
* @throws SecurityException
885
* If a security manager exists and its {@link
886
* java.lang.SecurityManager#checkRead(java.lang.String)}
887
* method denies read access to the file
888
*/
889
public boolean isFile() {
890
@SuppressWarnings("removal")
891
SecurityManager security = System.getSecurityManager();
892
if (security != null) {
893
security.checkRead(path);
894
}
895
if (isInvalid()) {
896
return false;
897
}
898
return fs.hasBooleanAttributes(this, FileSystem.BA_REGULAR);
899
}
900
901
/**
902
* Tests whether the file named by this abstract pathname is a hidden
903
* file. The exact definition of <em>hidden</em> is system-dependent. On
904
* UNIX systems, a file is considered to be hidden if its name begins with
905
* a period character ({@code '.'}). On Microsoft Windows systems, a file is
906
* considered to be hidden if it has been marked as such in the filesystem.
907
*
908
* @return {@code true} if and only if the file denoted by this
909
* abstract pathname is hidden according to the conventions of the
910
* underlying platform
911
*
912
* @throws SecurityException
913
* If a security manager exists and its {@link
914
* java.lang.SecurityManager#checkRead(java.lang.String)}
915
* method denies read access to the file
916
*
917
* @since 1.2
918
*/
919
public boolean isHidden() {
920
@SuppressWarnings("removal")
921
SecurityManager security = System.getSecurityManager();
922
if (security != null) {
923
security.checkRead(path);
924
}
925
if (isInvalid()) {
926
return false;
927
}
928
return fs.hasBooleanAttributes(this, FileSystem.BA_HIDDEN);
929
}
930
931
/**
932
* Returns the time that the file denoted by this abstract pathname was
933
* last modified.
934
*
935
* @apiNote
936
* While the unit of time of the return value is milliseconds, the
937
* granularity of the value depends on the underlying file system and may
938
* be larger. For example, some file systems use time stamps in units of
939
* seconds.
940
*
941
* <p> Where it is required to distinguish an I/O exception from the case
942
* where {@code 0L} is returned, or where several attributes of the
943
* same file are required at the same time, or where the time of last
944
* access or the creation time are required, then the {@link
945
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
946
* Files.readAttributes} method may be used. If however only the
947
* time of last modification is required, then the
948
* {@link java.nio.file.Files#getLastModifiedTime(Path,LinkOption[])
949
* Files.getLastModifiedTime} method may be used instead.
950
*
951
* @return A {@code long} value representing the time the file was
952
* last modified, measured in milliseconds since the epoch
953
* (00:00:00 GMT, January 1, 1970), or {@code 0L} if the
954
* file does not exist or if an I/O error occurs. The value may
955
* be negative indicating the number of milliseconds before the
956
* epoch
957
*
958
* @throws SecurityException
959
* If a security manager exists and its {@link
960
* java.lang.SecurityManager#checkRead(java.lang.String)}
961
* method denies read access to the file
962
*/
963
public long lastModified() {
964
@SuppressWarnings("removal")
965
SecurityManager security = System.getSecurityManager();
966
if (security != null) {
967
security.checkRead(path);
968
}
969
if (isInvalid()) {
970
return 0L;
971
}
972
return fs.getLastModifiedTime(this);
973
}
974
975
/**
976
* Returns the length of the file denoted by this abstract pathname.
977
* The return value is unspecified if this pathname denotes a directory.
978
*
979
* <p> Where it is required to distinguish an I/O exception from the case
980
* that {@code 0L} is returned, or where several attributes of the same file
981
* are required at the same time, then the {@link
982
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
983
* Files.readAttributes} method may be used.
984
*
985
* @return The length, in bytes, of the file denoted by this abstract
986
* pathname, or {@code 0L} if the file does not exist. Some
987
* operating systems may return {@code 0L} for pathnames
988
* denoting system-dependent entities such as devices or pipes.
989
*
990
* @throws SecurityException
991
* If a security manager exists and its {@link
992
* java.lang.SecurityManager#checkRead(java.lang.String)}
993
* method denies read access to the file
994
*/
995
public long length() {
996
@SuppressWarnings("removal")
997
SecurityManager security = System.getSecurityManager();
998
if (security != null) {
999
security.checkRead(path);
1000
}
1001
if (isInvalid()) {
1002
return 0L;
1003
}
1004
return fs.getLength(this);
1005
}
1006
1007
1008
/* -- File operations -- */
1009
1010
/**
1011
* Atomically creates a new, empty file named by this abstract pathname if
1012
* and only if a file with this name does not yet exist. The check for the
1013
* existence of the file and the creation of the file if it does not exist
1014
* are a single operation that is atomic with respect to all other
1015
* filesystem activities that might affect the file.
1016
* <P>
1017
* Note: this method should <i>not</i> be used for file-locking, as
1018
* the resulting protocol cannot be made to work reliably. The
1019
* {@link java.nio.channels.FileLock FileLock}
1020
* facility should be used instead.
1021
*
1022
* @return {@code true} if the named file does not exist and was
1023
* successfully created; {@code false} if the named file
1024
* already exists
1025
*
1026
* @throws IOException
1027
* If an I/O error occurred
1028
*
1029
* @throws SecurityException
1030
* If a security manager exists and its {@link
1031
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1032
* method denies write access to the file
1033
*
1034
* @since 1.2
1035
*/
1036
public boolean createNewFile() throws IOException {
1037
@SuppressWarnings("removal")
1038
SecurityManager security = System.getSecurityManager();
1039
if (security != null) security.checkWrite(path);
1040
if (isInvalid()) {
1041
throw new IOException("Invalid file path");
1042
}
1043
return fs.createFileExclusively(path);
1044
}
1045
1046
/**
1047
* Deletes the file or directory denoted by this abstract pathname. If
1048
* this pathname denotes a directory, then the directory must be empty in
1049
* order to be deleted.
1050
*
1051
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1052
* java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}
1053
* when a file cannot be deleted. This is useful for error reporting and to
1054
* diagnose why a file cannot be deleted.
1055
*
1056
* @return {@code true} if and only if the file or directory is
1057
* successfully deleted; {@code false} otherwise
1058
*
1059
* @throws SecurityException
1060
* If a security manager exists and its {@link
1061
* java.lang.SecurityManager#checkDelete} method denies
1062
* delete access to the file
1063
*/
1064
public boolean delete() {
1065
@SuppressWarnings("removal")
1066
SecurityManager security = System.getSecurityManager();
1067
if (security != null) {
1068
security.checkDelete(path);
1069
}
1070
if (isInvalid()) {
1071
return false;
1072
}
1073
return fs.delete(this);
1074
}
1075
1076
/**
1077
* Requests that the file or directory denoted by this abstract
1078
* pathname be deleted when the virtual machine terminates.
1079
* Files (or directories) are deleted in the reverse order that
1080
* they are registered. Invoking this method to delete a file or
1081
* directory that is already registered for deletion has no effect.
1082
* Deletion will be attempted only for normal termination of the
1083
* virtual machine, as defined by the Java Language Specification.
1084
*
1085
* <p> Once deletion has been requested, it is not possible to cancel the
1086
* request. This method should therefore be used with care.
1087
*
1088
* <P>
1089
* Note: this method should <i>not</i> be used for file-locking, as
1090
* the resulting protocol cannot be made to work reliably. The
1091
* {@link java.nio.channels.FileLock FileLock}
1092
* facility should be used instead.
1093
*
1094
* @throws SecurityException
1095
* If a security manager exists and its {@link
1096
* java.lang.SecurityManager#checkDelete} method denies
1097
* delete access to the file
1098
*
1099
* @see #delete
1100
*
1101
* @since 1.2
1102
*/
1103
public void deleteOnExit() {
1104
@SuppressWarnings("removal")
1105
SecurityManager security = System.getSecurityManager();
1106
if (security != null) {
1107
security.checkDelete(path);
1108
}
1109
if (isInvalid()) {
1110
return;
1111
}
1112
DeleteOnExitHook.add(path);
1113
}
1114
1115
/**
1116
* Returns an array of strings naming the files and directories in the
1117
* directory denoted by this abstract pathname.
1118
*
1119
* <p> If this abstract pathname does not denote a directory, then this
1120
* method returns {@code null}. Otherwise an array of strings is
1121
* returned, one for each file or directory in the directory. Names
1122
* denoting the directory itself and the directory's parent directory are
1123
* not included in the result. Each string is a file name rather than a
1124
* complete path.
1125
*
1126
* <p> There is no guarantee that the name strings in the resulting array
1127
* will appear in any specific order; they are not, in particular,
1128
* guaranteed to appear in alphabetical order.
1129
*
1130
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1131
* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to
1132
* open a directory and iterate over the names of the files in the directory.
1133
* This may use less resources when working with very large directories, and
1134
* may be more responsive when working with remote directories.
1135
*
1136
* @return An array of strings naming the files and directories in the
1137
* directory denoted by this abstract pathname. The array will be
1138
* empty if the directory is empty. Returns {@code null} if
1139
* this abstract pathname does not denote a directory, or if an
1140
* I/O error occurs.
1141
*
1142
* @throws SecurityException
1143
* If a security manager exists and its {@link
1144
* SecurityManager#checkRead(String)} method denies read access to
1145
* the directory
1146
*/
1147
public String[] list() {
1148
return normalizedList();
1149
}
1150
1151
/**
1152
* Returns an array of strings naming the files and directories in the
1153
* directory denoted by this abstract pathname. The strings are
1154
* ensured to represent normalized paths.
1155
*
1156
* @return An array of strings naming the files and directories in the
1157
* directory denoted by this abstract pathname. The array will be
1158
* empty if the directory is empty. Returns {@code null} if
1159
* this abstract pathname does not denote a directory, or if an
1160
* I/O error occurs.
1161
*
1162
* @throws SecurityException
1163
* If a security manager exists and its {@link
1164
* SecurityManager#checkRead(String)} method denies read access to
1165
* the directory
1166
*/
1167
private final String[] normalizedList() {
1168
@SuppressWarnings("removal")
1169
SecurityManager security = System.getSecurityManager();
1170
if (security != null) {
1171
security.checkRead(path);
1172
}
1173
if (isInvalid()) {
1174
return null;
1175
}
1176
String[] s = fs.list(this);
1177
if (s != null && getClass() != File.class) {
1178
String[] normalized = new String[s.length];
1179
for (int i = 0; i < s.length; i++) {
1180
normalized[i] = fs.normalize(s[i]);
1181
}
1182
s = normalized;
1183
}
1184
return s;
1185
}
1186
1187
/**
1188
* Returns an array of strings naming the files and directories in the
1189
* directory denoted by this abstract pathname that satisfy the specified
1190
* filter. The behavior of this method is the same as that of the
1191
* {@link #list()} method, except that the strings in the returned array
1192
* must satisfy the filter. If the given {@code filter} is {@code null}
1193
* then all names are accepted. Otherwise, a name satisfies the filter if
1194
* and only if the value {@code true} results when the {@link
1195
* FilenameFilter#accept FilenameFilter.accept(File,&nbsp;String)} method
1196
* of the filter is invoked on this abstract pathname and the name of a
1197
* file or directory in the directory that it denotes.
1198
*
1199
* @param filter
1200
* A filename filter
1201
*
1202
* @return An array of strings naming the files and directories in the
1203
* directory denoted by this abstract pathname that were accepted
1204
* by the given {@code filter}. The array will be empty if the
1205
* directory is empty or if no names were accepted by the filter.
1206
* Returns {@code null} if this abstract pathname does not denote
1207
* a directory, or if an I/O error occurs.
1208
*
1209
* @throws SecurityException
1210
* If a security manager exists and its {@link
1211
* SecurityManager#checkRead(String)} method denies read access to
1212
* the directory
1213
*
1214
* @see java.nio.file.Files#newDirectoryStream(Path,String)
1215
*/
1216
public String[] list(FilenameFilter filter) {
1217
String names[] = normalizedList();
1218
if ((names == null) || (filter == null)) {
1219
return names;
1220
}
1221
List<String> v = new ArrayList<>();
1222
for (int i = 0 ; i < names.length ; i++) {
1223
if (filter.accept(this, names[i])) {
1224
v.add(names[i]);
1225
}
1226
}
1227
return v.toArray(new String[v.size()]);
1228
}
1229
1230
/**
1231
* Returns an array of abstract pathnames denoting the files in the
1232
* directory denoted by this abstract pathname.
1233
*
1234
* <p> If this abstract pathname does not denote a directory, then this
1235
* method returns {@code null}. Otherwise an array of {@code File} objects
1236
* is returned, one for each file or directory in the directory. Pathnames
1237
* denoting the directory itself and the directory's parent directory are
1238
* not included in the result. Each resulting abstract pathname is
1239
* constructed from this abstract pathname using the {@link #File(File,
1240
* String) File(File,&nbsp;String)} constructor. Therefore if this
1241
* pathname is absolute then each resulting pathname is absolute; if this
1242
* pathname is relative then each resulting pathname will be relative to
1243
* the same directory.
1244
*
1245
* <p> There is no guarantee that the name strings in the resulting array
1246
* will appear in any specific order; they are not, in particular,
1247
* guaranteed to appear in alphabetical order.
1248
*
1249
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1250
* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method
1251
* to open a directory and iterate over the names of the files in the
1252
* directory. This may use less resources when working with very large
1253
* directories.
1254
*
1255
* @return An array of abstract pathnames denoting the files and
1256
* directories in the directory denoted by this abstract pathname.
1257
* The array will be empty if the directory is empty. Returns
1258
* {@code null} if this abstract pathname does not denote a
1259
* directory, or if an I/O error occurs.
1260
*
1261
* @throws SecurityException
1262
* If a security manager exists and its {@link
1263
* SecurityManager#checkRead(String)} method denies read access to
1264
* the directory
1265
*
1266
* @since 1.2
1267
*/
1268
public File[] listFiles() {
1269
String[] ss = normalizedList();
1270
if (ss == null) return null;
1271
int n = ss.length;
1272
File[] fs = new File[n];
1273
for (int i = 0; i < n; i++) {
1274
fs[i] = new File(ss[i], this);
1275
}
1276
return fs;
1277
}
1278
1279
/**
1280
* Returns an array of abstract pathnames denoting the files and
1281
* directories in the directory denoted by this abstract pathname that
1282
* satisfy the specified filter. The behavior of this method is the same
1283
* as that of the {@link #listFiles()} method, except that the pathnames in
1284
* the returned array must satisfy the filter. If the given {@code filter}
1285
* is {@code null} then all pathnames are accepted. Otherwise, a pathname
1286
* satisfies the filter if and only if the value {@code true} results when
1287
* the {@link FilenameFilter#accept
1288
* FilenameFilter.accept(File,&nbsp;String)} method of the filter is
1289
* invoked on this abstract pathname and the name of a file or directory in
1290
* the directory that it denotes.
1291
*
1292
* @param filter
1293
* A filename filter
1294
*
1295
* @return An array of abstract pathnames denoting the files and
1296
* directories in the directory denoted by this abstract pathname.
1297
* The array will be empty if the directory is empty. Returns
1298
* {@code null} if this abstract pathname does not denote a
1299
* directory, or if an I/O error occurs.
1300
*
1301
* @throws SecurityException
1302
* If a security manager exists and its {@link
1303
* SecurityManager#checkRead(String)} method denies read access to
1304
* the directory
1305
*
1306
* @since 1.2
1307
* @see java.nio.file.Files#newDirectoryStream(Path,String)
1308
*/
1309
public File[] listFiles(FilenameFilter filter) {
1310
String ss[] = normalizedList();
1311
if (ss == null) return null;
1312
ArrayList<File> files = new ArrayList<>();
1313
for (String s : ss)
1314
if ((filter == null) || filter.accept(this, s))
1315
files.add(new File(s, this));
1316
return files.toArray(new File[files.size()]);
1317
}
1318
1319
/**
1320
* Returns an array of abstract pathnames denoting the files and
1321
* directories in the directory denoted by this abstract pathname that
1322
* satisfy the specified filter. The behavior of this method is the same
1323
* as that of the {@link #listFiles()} method, except that the pathnames in
1324
* the returned array must satisfy the filter. If the given {@code filter}
1325
* is {@code null} then all pathnames are accepted. Otherwise, a pathname
1326
* satisfies the filter if and only if the value {@code true} results when
1327
* the {@link FileFilter#accept FileFilter.accept(File)} method of the
1328
* filter is invoked on the pathname.
1329
*
1330
* @param filter
1331
* A file filter
1332
*
1333
* @return An array of abstract pathnames denoting the files and
1334
* directories in the directory denoted by this abstract pathname.
1335
* The array will be empty if the directory is empty. Returns
1336
* {@code null} if this abstract pathname does not denote a
1337
* directory, or if an I/O error occurs.
1338
*
1339
* @throws SecurityException
1340
* If a security manager exists and its {@link
1341
* SecurityManager#checkRead(String)} method denies read access to
1342
* the directory
1343
*
1344
* @since 1.2
1345
* @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter)
1346
*/
1347
public File[] listFiles(FileFilter filter) {
1348
String ss[] = normalizedList();
1349
if (ss == null) return null;
1350
ArrayList<File> files = new ArrayList<>();
1351
for (String s : ss) {
1352
File f = new File(s, this);
1353
if ((filter == null) || filter.accept(f))
1354
files.add(f);
1355
}
1356
return files.toArray(new File[files.size()]);
1357
}
1358
1359
/**
1360
* Creates the directory named by this abstract pathname.
1361
*
1362
* @return {@code true} if and only if the directory was
1363
* created; {@code false} otherwise
1364
*
1365
* @throws SecurityException
1366
* If a security manager exists and its {@link
1367
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1368
* method does not permit the named directory to be created
1369
*/
1370
public boolean mkdir() {
1371
@SuppressWarnings("removal")
1372
SecurityManager security = System.getSecurityManager();
1373
if (security != null) {
1374
security.checkWrite(path);
1375
}
1376
if (isInvalid()) {
1377
return false;
1378
}
1379
return fs.createDirectory(this);
1380
}
1381
1382
/**
1383
* Creates the directory named by this abstract pathname, including any
1384
* necessary but nonexistent parent directories. Note that if this
1385
* operation fails it may have succeeded in creating some of the necessary
1386
* parent directories.
1387
*
1388
* @return {@code true} if and only if the directory was created,
1389
* along with all necessary parent directories; {@code false}
1390
* otherwise
1391
*
1392
* @throws SecurityException
1393
* If a security manager exists and its {@link
1394
* java.lang.SecurityManager#checkRead(java.lang.String)}
1395
* method does not permit verification of the existence of the
1396
* named directory and all necessary parent directories; or if
1397
* the {@link
1398
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1399
* method does not permit the named directory and all necessary
1400
* parent directories to be created
1401
*/
1402
public boolean mkdirs() {
1403
if (exists()) {
1404
return false;
1405
}
1406
if (mkdir()) {
1407
return true;
1408
}
1409
File canonFile = null;
1410
try {
1411
canonFile = getCanonicalFile();
1412
} catch (IOException e) {
1413
return false;
1414
}
1415
1416
File parent = canonFile.getParentFile();
1417
return (parent != null && (parent.mkdirs() || parent.exists()) &&
1418
canonFile.mkdir());
1419
}
1420
1421
/**
1422
* Renames the file denoted by this abstract pathname.
1423
*
1424
* <p> Many aspects of the behavior of this method are inherently
1425
* platform-dependent: The rename operation might not be able to move a
1426
* file from one filesystem to another, it might not be atomic, and it
1427
* might not succeed if a file with the destination abstract pathname
1428
* already exists. The return value should always be checked to make sure
1429
* that the rename operation was successful. As instances of {@code File}
1430
* are immutable, this File object is not changed to name the destination
1431
* file or directory.
1432
*
1433
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1434
* java.nio.file.Files#move move} method to move or rename a file in a
1435
* platform independent manner.
1436
*
1437
* @param dest The new abstract pathname for the named file
1438
*
1439
* @return {@code true} if and only if the renaming succeeded;
1440
* {@code false} otherwise
1441
*
1442
* @throws SecurityException
1443
* If a security manager exists and its {@link
1444
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1445
* method denies write access to either the old or new pathnames
1446
*
1447
* @throws NullPointerException
1448
* If parameter {@code dest} is {@code null}
1449
*/
1450
public boolean renameTo(File dest) {
1451
if (dest == null) {
1452
throw new NullPointerException();
1453
}
1454
@SuppressWarnings("removal")
1455
SecurityManager security = System.getSecurityManager();
1456
if (security != null) {
1457
security.checkWrite(path);
1458
security.checkWrite(dest.path);
1459
}
1460
if (this.isInvalid() || dest.isInvalid()) {
1461
return false;
1462
}
1463
return fs.rename(this, dest);
1464
}
1465
1466
/**
1467
* Sets the last-modified time of the file or directory named by this
1468
* abstract pathname.
1469
*
1470
* <p> All platforms support file-modification times to the nearest second,
1471
* but some provide more precision. The argument will be truncated to fit
1472
* the supported precision. If the operation succeeds and no intervening
1473
* operations on the file take place, then the next invocation of the
1474
* {@link #lastModified} method will return the (possibly
1475
* truncated) {@code time} argument that was passed to this method.
1476
*
1477
* @param time The new last-modified time, measured in milliseconds since
1478
* the epoch (00:00:00 GMT, January 1, 1970)
1479
*
1480
* @return {@code true} if and only if the operation succeeded;
1481
* {@code false} otherwise
1482
*
1483
* @throws IllegalArgumentException If the argument is negative
1484
*
1485
* @throws SecurityException
1486
* If a security manager exists and its {@link
1487
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1488
* method denies write access to the named file
1489
*
1490
* @since 1.2
1491
*/
1492
public boolean setLastModified(long time) {
1493
if (time < 0) throw new IllegalArgumentException("Negative time");
1494
@SuppressWarnings("removal")
1495
SecurityManager security = System.getSecurityManager();
1496
if (security != null) {
1497
security.checkWrite(path);
1498
}
1499
if (isInvalid()) {
1500
return false;
1501
}
1502
return fs.setLastModifiedTime(this, time);
1503
}
1504
1505
/**
1506
* Marks the file or directory named by this abstract pathname so that
1507
* only read operations are allowed. After invoking this method the file
1508
* or directory will not change until it is either deleted or marked
1509
* to allow write access. On some platforms it may be possible to start the
1510
* Java virtual machine with special privileges that allow it to modify
1511
* files that are marked read-only. Whether or not a read-only file or
1512
* directory may be deleted depends upon the underlying system.
1513
*
1514
* @return {@code true} if and only if the operation succeeded;
1515
* {@code false} otherwise
1516
*
1517
* @throws SecurityException
1518
* If a security manager exists and its {@link
1519
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1520
* method denies write access to the named file
1521
*
1522
* @since 1.2
1523
*/
1524
public boolean setReadOnly() {
1525
@SuppressWarnings("removal")
1526
SecurityManager security = System.getSecurityManager();
1527
if (security != null) {
1528
security.checkWrite(path);
1529
}
1530
if (isInvalid()) {
1531
return false;
1532
}
1533
return fs.setReadOnly(this);
1534
}
1535
1536
/**
1537
* Sets the owner's or everybody's write permission for this abstract
1538
* pathname. On some platforms it may be possible to start the Java virtual
1539
* machine with special privileges that allow it to modify files that
1540
* disallow write operations.
1541
*
1542
* <p> The {@link java.nio.file.Files} class defines methods that operate on
1543
* file attributes including file permissions. This may be used when finer
1544
* manipulation of file permissions is required.
1545
*
1546
* @param writable
1547
* If {@code true}, sets the access permission to allow write
1548
* operations; if {@code false} to disallow write operations
1549
*
1550
* @param ownerOnly
1551
* If {@code true}, the write permission applies only to the
1552
* owner's write permission; otherwise, it applies to everybody. If
1553
* the underlying file system can not distinguish the owner's write
1554
* permission from that of others, then the permission will apply to
1555
* everybody, regardless of this value.
1556
*
1557
* @return {@code true} if and only if the operation succeeded. The
1558
* operation will fail if the user does not have permission to change
1559
* the access permissions of this abstract pathname.
1560
*
1561
* @throws SecurityException
1562
* If a security manager exists and its {@link
1563
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1564
* method denies write access to the named file
1565
*
1566
* @since 1.6
1567
*/
1568
public boolean setWritable(boolean writable, boolean ownerOnly) {
1569
@SuppressWarnings("removal")
1570
SecurityManager security = System.getSecurityManager();
1571
if (security != null) {
1572
security.checkWrite(path);
1573
}
1574
if (isInvalid()) {
1575
return false;
1576
}
1577
return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly);
1578
}
1579
1580
/**
1581
* A convenience method to set the owner's write permission for this abstract
1582
* pathname. On some platforms it may be possible to start the Java virtual
1583
* machine with special privileges that allow it to modify files that
1584
* disallow write operations.
1585
*
1586
* <p> An invocation of this method of the form {@code file.setWritable(arg)}
1587
* behaves in exactly the same way as the invocation
1588
*
1589
* <pre>{@code
1590
* file.setWritable(arg, true)
1591
* }</pre>
1592
*
1593
* @param writable
1594
* If {@code true}, sets the access permission to allow write
1595
* operations; if {@code false} to disallow write operations
1596
*
1597
* @return {@code true} if and only if the operation succeeded. The
1598
* operation will fail if the user does not have permission to
1599
* change the access permissions of this abstract pathname.
1600
*
1601
* @throws SecurityException
1602
* If a security manager exists and its {@link
1603
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1604
* method denies write access to the file
1605
*
1606
* @since 1.6
1607
*/
1608
public boolean setWritable(boolean writable) {
1609
return setWritable(writable, true);
1610
}
1611
1612
/**
1613
* Sets the owner's or everybody's read permission for this abstract
1614
* pathname. On some platforms it may be possible to start the Java virtual
1615
* machine with special privileges that allow it to read files that are
1616
* marked as unreadable.
1617
*
1618
* <p> The {@link java.nio.file.Files} class defines methods that operate on
1619
* file attributes including file permissions. This may be used when finer
1620
* manipulation of file permissions is required.
1621
*
1622
* @param readable
1623
* If {@code true}, sets the access permission to allow read
1624
* operations; if {@code false} to disallow read operations
1625
*
1626
* @param ownerOnly
1627
* If {@code true}, the read permission applies only to the
1628
* owner's read permission; otherwise, it applies to everybody. If
1629
* the underlying file system can not distinguish the owner's read
1630
* permission from that of others, then the permission will apply to
1631
* everybody, regardless of this value.
1632
*
1633
* @return {@code true} if and only if the operation succeeded. The
1634
* operation will fail if the user does not have permission to
1635
* change the access permissions of this abstract pathname. If
1636
* {@code readable} is {@code false} and the underlying
1637
* file system does not implement a read permission, then the
1638
* operation will fail.
1639
*
1640
* @throws SecurityException
1641
* If a security manager exists and its {@link
1642
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1643
* method denies write access to the file
1644
*
1645
* @since 1.6
1646
*/
1647
public boolean setReadable(boolean readable, boolean ownerOnly) {
1648
@SuppressWarnings("removal")
1649
SecurityManager security = System.getSecurityManager();
1650
if (security != null) {
1651
security.checkWrite(path);
1652
}
1653
if (isInvalid()) {
1654
return false;
1655
}
1656
return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);
1657
}
1658
1659
/**
1660
* A convenience method to set the owner's read permission for this abstract
1661
* pathname. On some platforms it may be possible to start the Java virtual
1662
* machine with special privileges that allow it to read files that are
1663
* marked as unreadable.
1664
*
1665
* <p>An invocation of this method of the form {@code file.setReadable(arg)}
1666
* behaves in exactly the same way as the invocation
1667
*
1668
* <pre>{@code
1669
* file.setReadable(arg, true)
1670
* }</pre>
1671
*
1672
* @param readable
1673
* If {@code true}, sets the access permission to allow read
1674
* operations; if {@code false} to disallow read operations
1675
*
1676
* @return {@code true} if and only if the operation succeeded. The
1677
* operation will fail if the user does not have permission to
1678
* change the access permissions of this abstract pathname. If
1679
* {@code readable} is {@code false} and the underlying
1680
* file system does not implement a read permission, then the
1681
* operation will fail.
1682
*
1683
* @throws SecurityException
1684
* If a security manager exists and its {@link
1685
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1686
* method denies write access to the file
1687
*
1688
* @since 1.6
1689
*/
1690
public boolean setReadable(boolean readable) {
1691
return setReadable(readable, true);
1692
}
1693
1694
/**
1695
* Sets the owner's or everybody's execute permission for this abstract
1696
* pathname. On some platforms it may be possible to start the Java virtual
1697
* machine with special privileges that allow it to execute files that are
1698
* not marked executable.
1699
*
1700
* <p> The {@link java.nio.file.Files} class defines methods that operate on
1701
* file attributes including file permissions. This may be used when finer
1702
* manipulation of file permissions is required.
1703
*
1704
* @param executable
1705
* If {@code true}, sets the access permission to allow execute
1706
* operations; if {@code false} to disallow execute operations
1707
*
1708
* @param ownerOnly
1709
* If {@code true}, the execute permission applies only to the
1710
* owner's execute permission; otherwise, it applies to everybody.
1711
* If the underlying file system can not distinguish the owner's
1712
* execute permission from that of others, then the permission will
1713
* apply to everybody, regardless of this value.
1714
*
1715
* @return {@code true} if and only if the operation succeeded. The
1716
* operation will fail if the user does not have permission to
1717
* change the access permissions of this abstract pathname. If
1718
* {@code executable} is {@code false} and the underlying
1719
* file system does not implement an execute permission, then the
1720
* operation will fail.
1721
*
1722
* @throws SecurityException
1723
* If a security manager exists and its {@link
1724
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1725
* method denies write access to the file
1726
*
1727
* @since 1.6
1728
*/
1729
public boolean setExecutable(boolean executable, boolean ownerOnly) {
1730
@SuppressWarnings("removal")
1731
SecurityManager security = System.getSecurityManager();
1732
if (security != null) {
1733
security.checkWrite(path);
1734
}
1735
if (isInvalid()) {
1736
return false;
1737
}
1738
return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);
1739
}
1740
1741
/**
1742
* A convenience method to set the owner's execute permission for this
1743
* abstract pathname. On some platforms it may be possible to start the Java
1744
* virtual machine with special privileges that allow it to execute files
1745
* that are not marked executable.
1746
*
1747
* <p>An invocation of this method of the form {@code file.setExcutable(arg)}
1748
* behaves in exactly the same way as the invocation
1749
*
1750
* <pre>{@code
1751
* file.setExecutable(arg, true)
1752
* }</pre>
1753
*
1754
* @param executable
1755
* If {@code true}, sets the access permission to allow execute
1756
* operations; if {@code false} to disallow execute operations
1757
*
1758
* @return {@code true} if and only if the operation succeeded. The
1759
* operation will fail if the user does not have permission to
1760
* change the access permissions of this abstract pathname. If
1761
* {@code executable} is {@code false} and the underlying
1762
* file system does not implement an execute permission, then the
1763
* operation will fail.
1764
*
1765
* @throws SecurityException
1766
* If a security manager exists and its {@link
1767
* java.lang.SecurityManager#checkWrite(java.lang.String)}
1768
* method denies write access to the file
1769
*
1770
* @since 1.6
1771
*/
1772
public boolean setExecutable(boolean executable) {
1773
return setExecutable(executable, true);
1774
}
1775
1776
/**
1777
* Tests whether the application can execute the file denoted by this
1778
* abstract pathname. On some platforms it may be possible to start the
1779
* Java virtual machine with special privileges that allow it to execute
1780
* files that are not marked executable. Consequently this method may return
1781
* {@code true} even though the file does not have execute permissions.
1782
*
1783
* @return {@code true} if and only if the abstract pathname exists
1784
* <em>and</em> the application is allowed to execute the file
1785
*
1786
* @throws SecurityException
1787
* If a security manager exists and its {@link
1788
* java.lang.SecurityManager#checkExec(java.lang.String)}
1789
* method denies execute access to the file
1790
*
1791
* @since 1.6
1792
*/
1793
public boolean canExecute() {
1794
@SuppressWarnings("removal")
1795
SecurityManager security = System.getSecurityManager();
1796
if (security != null) {
1797
security.checkExec(path);
1798
}
1799
if (isInvalid()) {
1800
return false;
1801
}
1802
return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);
1803
}
1804
1805
1806
/* -- Filesystem interface -- */
1807
1808
/**
1809
* List the available filesystem roots.
1810
*
1811
* <p> A particular Java platform may support zero or more
1812
* hierarchically-organized file systems. Each file system has a
1813
* {@code root} directory from which all other files in that file system
1814
* can be reached. Windows platforms, for example, have a root directory
1815
* for each active drive; UNIX platforms have a single root directory,
1816
* namely {@code "/"}. The set of available filesystem roots is affected
1817
* by various system-level operations such as the insertion or ejection of
1818
* removable media and the disconnecting or unmounting of physical or
1819
* virtual disk drives.
1820
*
1821
* <p> This method returns an array of {@code File} objects that denote the
1822
* root directories of the available filesystem roots. It is guaranteed
1823
* that the canonical pathname of any file physically present on the local
1824
* machine will begin with one of the roots returned by this method.
1825
*
1826
* <p> The canonical pathname of a file that resides on some other machine
1827
* and is accessed via a remote-filesystem protocol such as SMB or NFS may
1828
* or may not begin with one of the roots returned by this method. If the
1829
* pathname of a remote file is syntactically indistinguishable from the
1830
* pathname of a local file then it will begin with one of the roots
1831
* returned by this method. Thus, for example, {@code File} objects
1832
* denoting the root directories of the mapped network drives of a Windows
1833
* platform will be returned by this method, while {@code File} objects
1834
* containing UNC pathnames will not be returned by this method.
1835
*
1836
* <p> Unlike most methods in this class, this method does not throw
1837
* security exceptions. If a security manager exists and its {@link
1838
* SecurityManager#checkRead(String)} method denies read access to a
1839
* particular root directory, then that directory will not appear in the
1840
* result.
1841
*
1842
* @return An array of {@code File} objects denoting the available
1843
* filesystem roots, or {@code null} if the set of roots could not
1844
* be determined. The array will be empty if there are no
1845
* filesystem roots.
1846
*
1847
* @since 1.2
1848
* @see java.nio.file.FileStore
1849
*/
1850
public static File[] listRoots() {
1851
return fs.listRoots();
1852
}
1853
1854
1855
/* -- Disk usage -- */
1856
1857
/**
1858
* Returns the size of the partition <a href="#partName">named</a> by this
1859
* abstract pathname. If the total number of bytes in the partition is
1860
* greater than {@link Long#MAX_VALUE}, then {@code Long.MAX_VALUE} will be
1861
* returned.
1862
*
1863
* @return The size, in bytes, of the partition or {@code 0L} if this
1864
* abstract pathname does not name a partition or if the size
1865
* cannot be obtained
1866
*
1867
* @throws SecurityException
1868
* If a security manager has been installed and it denies
1869
* {@link RuntimePermission}{@code ("getFileSystemAttributes")}
1870
* or its {@link SecurityManager#checkRead(String)} method denies
1871
* read access to the file named by this abstract pathname
1872
*
1873
* @since 1.6
1874
* @see FileStore#getTotalSpace
1875
*/
1876
public long getTotalSpace() {
1877
@SuppressWarnings("removal")
1878
SecurityManager sm = System.getSecurityManager();
1879
if (sm != null) {
1880
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1881
sm.checkRead(path);
1882
}
1883
if (isInvalid()) {
1884
return 0L;
1885
}
1886
long space = fs.getSpace(this, FileSystem.SPACE_TOTAL);
1887
return space >= 0L ? space : Long.MAX_VALUE;
1888
}
1889
1890
/**
1891
* Returns the number of unallocated bytes in the partition <a
1892
* href="#partName">named</a> by this abstract path name. If the
1893
* number of unallocated bytes in the partition is greater than
1894
* {@link Long#MAX_VALUE}, then {@code Long.MAX_VALUE} will be returned.
1895
*
1896
* <p> The returned number of unallocated bytes is a hint, but not
1897
* a guarantee, that it is possible to use most or any of these
1898
* bytes. The number of unallocated bytes is most likely to be
1899
* accurate immediately after this call. It is likely to be made
1900
* inaccurate by any external I/O operations including those made
1901
* on the system outside of this virtual machine. This method
1902
* makes no guarantee that write operations to this file system
1903
* will succeed.
1904
*
1905
* @return The number of unallocated bytes on the partition or {@code 0L}
1906
* if the abstract pathname does not name a partition or if this
1907
* number cannot be obtained. This value will be less than or
1908
* equal to the total file system size returned by
1909
* {@link #getTotalSpace}.
1910
*
1911
* @throws SecurityException
1912
* If a security manager has been installed and it denies
1913
* {@link RuntimePermission}{@code ("getFileSystemAttributes")}
1914
* or its {@link SecurityManager#checkRead(String)} method denies
1915
* read access to the file named by this abstract pathname
1916
*
1917
* @since 1.6
1918
* @see FileStore#getUnallocatedSpace
1919
*/
1920
public long getFreeSpace() {
1921
@SuppressWarnings("removal")
1922
SecurityManager sm = System.getSecurityManager();
1923
if (sm != null) {
1924
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1925
sm.checkRead(path);
1926
}
1927
if (isInvalid()) {
1928
return 0L;
1929
}
1930
long space = fs.getSpace(this, FileSystem.SPACE_FREE);
1931
return space >= 0L ? space : Long.MAX_VALUE;
1932
}
1933
1934
/**
1935
* Returns the number of bytes available to this virtual machine on the
1936
* partition <a href="#partName">named</a> by this abstract pathname. If
1937
* the number of available bytes in the partition is greater than
1938
* {@link Long#MAX_VALUE}, then {@code Long.MAX_VALUE} will be returned.
1939
* When possible, this method checks for write permissions and other
1940
* operating system restrictions and will therefore usually provide a more
1941
* accurate estimate of how much new data can actually be written than
1942
* {@link #getFreeSpace}.
1943
*
1944
* <p> The returned number of available bytes is a hint, but not a
1945
* guarantee, that it is possible to use most or any of these bytes. The
1946
* number of available bytes is most likely to be accurate immediately
1947
* after this call. It is likely to be made inaccurate by any external
1948
* I/O operations including those made on the system outside of this
1949
* virtual machine. This method makes no guarantee that write operations
1950
* to this file system will succeed.
1951
*
1952
* @return The number of available bytes on the partition or {@code 0L}
1953
* if the abstract pathname does not name a partition or if this
1954
* number cannot be obtained. On systems where this information
1955
* is not available, this method will be equivalent to a call to
1956
* {@link #getFreeSpace}.
1957
*
1958
* @throws SecurityException
1959
* If a security manager has been installed and it denies
1960
* {@link RuntimePermission}{@code ("getFileSystemAttributes")}
1961
* or its {@link SecurityManager#checkRead(String)} method denies
1962
* read access to the file named by this abstract pathname
1963
*
1964
* @since 1.6
1965
* @see FileStore#getUsableSpace
1966
*/
1967
public long getUsableSpace() {
1968
@SuppressWarnings("removal")
1969
SecurityManager sm = System.getSecurityManager();
1970
if (sm != null) {
1971
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1972
sm.checkRead(path);
1973
}
1974
if (isInvalid()) {
1975
return 0L;
1976
}
1977
long space = fs.getSpace(this, FileSystem.SPACE_USABLE);
1978
return space >= 0L ? space : Long.MAX_VALUE;
1979
}
1980
1981
/* -- Temporary files -- */
1982
1983
private static class TempDirectory {
1984
private TempDirectory() { }
1985
1986
// temporary directory location
1987
private static final File tmpdir = new File(
1988
GetPropertyAction.privilegedGetProperty("java.io.tmpdir"));
1989
static File location() {
1990
return tmpdir;
1991
}
1992
1993
// file name generation
1994
private static final SecureRandom random = new SecureRandom();
1995
private static int shortenSubName(int subNameLength, int excess,
1996
int nameMin) {
1997
int newLength = Math.max(nameMin, subNameLength - excess);
1998
if (newLength < subNameLength) {
1999
return newLength;
2000
}
2001
return subNameLength;
2002
}
2003
@SuppressWarnings("removal")
2004
static File generateFile(String prefix, String suffix, File dir)
2005
throws IOException
2006
{
2007
long n = random.nextLong();
2008
String nus = Long.toUnsignedString(n);
2009
2010
// Use only the file name from the supplied prefix
2011
prefix = (new File(prefix)).getName();
2012
2013
int prefixLength = prefix.length();
2014
int nusLength = nus.length();
2015
int suffixLength = suffix.length();;
2016
2017
String name;
2018
int nameMax = fs.getNameMax(dir.getPath());
2019
int excess = prefixLength + nusLength + suffixLength - nameMax;
2020
if (excess <= 0) {
2021
name = prefix + nus + suffix;
2022
} else {
2023
// Name exceeds the maximum path component length: shorten it
2024
2025
// Attempt to shorten the prefix length to no less then 3
2026
prefixLength = shortenSubName(prefixLength, excess, 3);
2027
excess = prefixLength + nusLength + suffixLength - nameMax;
2028
2029
if (excess > 0) {
2030
// Attempt to shorten the suffix length to no less than
2031
// 0 or 4 depending on whether it begins with a dot ('.')
2032
suffixLength = shortenSubName(suffixLength, excess,
2033
suffix.indexOf(".") == 0 ? 4 : 0);
2034
suffixLength = shortenSubName(suffixLength, excess, 3);
2035
excess = prefixLength + nusLength + suffixLength - nameMax;
2036
}
2037
2038
if (excess > 0 && excess <= nusLength - 5) {
2039
// Attempt to shorten the random character string length
2040
// to no less than 5
2041
nusLength = shortenSubName(nusLength, excess, 5);
2042
}
2043
2044
StringBuilder sb =
2045
new StringBuilder(prefixLength + nusLength + suffixLength);
2046
sb.append(prefixLength < prefix.length() ?
2047
prefix.substring(0, prefixLength) : prefix);
2048
sb.append(nusLength < nus.length() ?
2049
nus.substring(0, nusLength) : nus);
2050
sb.append(suffixLength < suffix.length() ?
2051
suffix.substring(0, suffixLength) : suffix);
2052
name = sb.toString();
2053
}
2054
2055
// Normalize the path component
2056
name = fs.normalize(name);
2057
2058
File f = new File(dir, name);
2059
if (!name.equals(f.getName()) || f.isInvalid()) {
2060
if (System.getSecurityManager() != null)
2061
throw new IOException("Unable to create temporary file");
2062
else
2063
throw new IOException("Unable to create temporary file, "
2064
+ name);
2065
}
2066
return f;
2067
}
2068
}
2069
2070
/**
2071
* <p> Creates a new empty file in the specified directory, using the
2072
* given prefix and suffix strings to generate its name. If this method
2073
* returns successfully then it is guaranteed that:
2074
*
2075
* <ol>
2076
* <li> The file denoted by the returned abstract pathname did not exist
2077
* before this method was invoked, and
2078
* <li> Neither this method nor any of its variants will return the same
2079
* abstract pathname again in the current invocation of the virtual
2080
* machine.
2081
* </ol>
2082
*
2083
* This method provides only part of a temporary-file facility. To arrange
2084
* for a file created by this method to be deleted automatically, use the
2085
* {@link #deleteOnExit} method.
2086
*
2087
* <p> The {@code prefix} argument must be at least three characters
2088
* long. It is recommended that the prefix be a short, meaningful string
2089
* such as {@code "hjb"} or {@code "mail"}. The
2090
* {@code suffix} argument may be {@code null}, in which case the
2091
* suffix {@code ".tmp"} will be used.
2092
*
2093
* <p> To create the new file, the prefix and the suffix may first be
2094
* adjusted to fit the limitations of the underlying platform. If the
2095
* prefix is too long then it will be truncated, but its first three
2096
* characters will always be preserved. If the suffix is too long then it
2097
* too will be truncated, but if it begins with a period character
2098
* ({@code '.'}) then the period and the first three characters
2099
* following it will always be preserved. Once these adjustments have been
2100
* made the name of the new file will be generated by concatenating the
2101
* prefix, five or more internally-generated characters, and the suffix.
2102
*
2103
* <p> If the {@code directory} argument is {@code null} then the
2104
* system-dependent default temporary-file directory will be used. The
2105
* default temporary-file directory is specified by the system property
2106
* {@code java.io.tmpdir}. On UNIX systems the default value of this
2107
* property is typically {@code "/tmp"} or {@code "/var/tmp"}; on
2108
* Microsoft Windows systems it is typically {@code "C:\\WINNT\\TEMP"}. A different
2109
* value may be given to this system property when the Java virtual machine
2110
* is invoked, but programmatic changes to this property are not guaranteed
2111
* to have any effect upon the temporary directory used by this method.
2112
*
2113
* @param prefix The prefix string to be used in generating the file's
2114
* name; must be at least three characters long
2115
*
2116
* @param suffix The suffix string to be used in generating the file's
2117
* name; may be {@code null}, in which case the
2118
* suffix {@code ".tmp"} will be used
2119
*
2120
* @param directory The directory in which the file is to be created, or
2121
* {@code null} if the default temporary-file
2122
* directory is to be used
2123
*
2124
* @return An abstract pathname denoting a newly-created empty file
2125
*
2126
* @throws IllegalArgumentException
2127
* If the {@code prefix} argument contains fewer than three
2128
* characters
2129
*
2130
* @throws IOException If a file could not be created
2131
*
2132
* @throws SecurityException
2133
* If a security manager exists and its {@link
2134
* java.lang.SecurityManager#checkWrite(java.lang.String)}
2135
* method does not allow a file to be created
2136
*
2137
* @since 1.2
2138
*/
2139
public static File createTempFile(String prefix, String suffix,
2140
File directory)
2141
throws IOException
2142
{
2143
if (prefix.length() < 3) {
2144
throw new IllegalArgumentException("Prefix string \"" + prefix +
2145
"\" too short: length must be at least 3");
2146
}
2147
if (suffix == null)
2148
suffix = ".tmp";
2149
2150
File tmpdir = (directory != null) ? directory
2151
: TempDirectory.location();
2152
@SuppressWarnings("removal")
2153
SecurityManager sm = System.getSecurityManager();
2154
File f;
2155
do {
2156
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
2157
2158
if (sm != null) {
2159
try {
2160
sm.checkWrite(f.getPath());
2161
} catch (SecurityException se) {
2162
// don't reveal temporary directory location
2163
if (directory == null)
2164
throw new SecurityException("Unable to create temporary file");
2165
throw se;
2166
}
2167
}
2168
} while (fs.hasBooleanAttributes(f, FileSystem.BA_EXISTS));
2169
2170
if (!fs.createFileExclusively(f.getPath()))
2171
throw new IOException("Unable to create temporary file");
2172
2173
return f;
2174
}
2175
2176
/**
2177
* Creates an empty file in the default temporary-file directory, using
2178
* the given prefix and suffix to generate its name. Invoking this method
2179
* is equivalent to invoking {@link #createTempFile(java.lang.String,
2180
* java.lang.String, java.io.File)
2181
* createTempFile(prefix,&nbsp;suffix,&nbsp;null)}.
2182
*
2183
* <p> The {@link
2184
* java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[])
2185
* Files.createTempFile} method provides an alternative method to create an
2186
* empty file in the temporary-file directory. Files created by that method
2187
* may have more restrictive access permissions to files created by this
2188
* method and so may be more suited to security-sensitive applications.
2189
*
2190
* @param prefix The prefix string to be used in generating the file's
2191
* name; must be at least three characters long
2192
*
2193
* @param suffix The suffix string to be used in generating the file's
2194
* name; may be {@code null}, in which case the
2195
* suffix {@code ".tmp"} will be used
2196
*
2197
* @return An abstract pathname denoting a newly-created empty file
2198
*
2199
* @throws IllegalArgumentException
2200
* If the {@code prefix} argument contains fewer than three
2201
* characters
2202
*
2203
* @throws IOException If a file could not be created
2204
*
2205
* @throws SecurityException
2206
* If a security manager exists and its {@link
2207
* java.lang.SecurityManager#checkWrite(java.lang.String)}
2208
* method does not allow a file to be created
2209
*
2210
* @since 1.2
2211
* @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])
2212
*/
2213
public static File createTempFile(String prefix, String suffix)
2214
throws IOException
2215
{
2216
return createTempFile(prefix, suffix, null);
2217
}
2218
2219
/* -- Basic infrastructure -- */
2220
2221
/**
2222
* Compares two abstract pathnames lexicographically. The ordering
2223
* defined by this method depends upon the underlying system. On UNIX
2224
* systems, alphabetic case is significant in comparing pathnames; on
2225
* Microsoft Windows systems it is not.
2226
*
2227
* @param pathname The abstract pathname to be compared to this abstract
2228
* pathname
2229
*
2230
* @return Zero if the argument is equal to this abstract pathname, a
2231
* value less than zero if this abstract pathname is
2232
* lexicographically less than the argument, or a value greater
2233
* than zero if this abstract pathname is lexicographically
2234
* greater than the argument
2235
*
2236
* @since 1.2
2237
*/
2238
public int compareTo(File pathname) {
2239
return fs.compare(this, pathname);
2240
}
2241
2242
/**
2243
* Tests this abstract pathname for equality with the given object.
2244
* Returns {@code true} if and only if the argument is not
2245
* {@code null} and is an abstract pathname that is the same as this
2246
* abstract pathname. Whether or not two abstract
2247
* pathnames are equal depends upon the underlying operating system.
2248
* On UNIX systems, alphabetic case is significant in comparing pathnames;
2249
* on Microsoft Windows systems it is not.
2250
*
2251
* @apiNote This method only tests whether the abstract pathnames are equal;
2252
* it does not access the file system and the file is not required
2253
* to exist.
2254
*
2255
* @param obj The object to be compared with this abstract pathname
2256
*
2257
* @return {@code true} if and only if the objects are the same;
2258
* {@code false} otherwise
2259
*
2260
* @see #compareTo(File)
2261
* @see java.nio.file.Files#isSameFile(Path,Path)
2262
*/
2263
public boolean equals(Object obj) {
2264
if (obj instanceof File file) {
2265
return compareTo(file) == 0;
2266
}
2267
return false;
2268
}
2269
2270
/**
2271
* Computes a hash code for this abstract pathname. Because equality of
2272
* abstract pathnames is inherently system-dependent, so is the computation
2273
* of their hash codes. On UNIX systems, the hash code of an abstract
2274
* pathname is equal to the exclusive <em>or</em> of the hash code
2275
* of its pathname string and the decimal value
2276
* {@code 1234321}. On Microsoft Windows systems, the hash
2277
* code is equal to the exclusive <em>or</em> of the hash code of
2278
* its pathname string converted to lower case and the decimal
2279
* value {@code 1234321}. Locale is not taken into account on
2280
* lowercasing the pathname string.
2281
*
2282
* @return A hash code for this abstract pathname
2283
*/
2284
public int hashCode() {
2285
return fs.hashCode(this);
2286
}
2287
2288
/**
2289
* Returns the pathname string of this abstract pathname. This is just the
2290
* string returned by the {@link #getPath} method.
2291
*
2292
* @return The string form of this abstract pathname
2293
*/
2294
public String toString() {
2295
return getPath();
2296
}
2297
2298
/**
2299
* WriteObject is called to save this filename.
2300
* The separator character is saved also so it can be replaced
2301
* in case the path is reconstituted on a different host type.
2302
*
2303
* @serialData Default fields followed by separator character.
2304
*
2305
* @param s the {@code ObjectOutputStream} to which data is written
2306
* @throws IOException if an I/O error occurs
2307
*/
2308
@java.io.Serial
2309
private synchronized void writeObject(java.io.ObjectOutputStream s)
2310
throws IOException
2311
{
2312
s.defaultWriteObject();
2313
s.writeChar(separatorChar); // Add the separator character
2314
}
2315
2316
/**
2317
* readObject is called to restore this filename.
2318
* The original separator character is read. If it is different
2319
* than the separator character on this system, then the old separator
2320
* is replaced by the local separator.
2321
*
2322
* @param s the {@code ObjectInputStream} from which data is read
2323
* @throws IOException if an I/O error occurs
2324
* @throws ClassNotFoundException if a serialized class cannot be loaded
2325
*/
2326
@java.io.Serial
2327
private synchronized void readObject(java.io.ObjectInputStream s)
2328
throws IOException, ClassNotFoundException
2329
{
2330
ObjectInputStream.GetField fields = s.readFields();
2331
String pathField = (String)fields.get("path", null);
2332
char sep = s.readChar(); // read the previous separator char
2333
if (sep != separatorChar)
2334
pathField = pathField.replace(sep, separatorChar);
2335
String path = fs.normalize(pathField);
2336
UNSAFE.putReference(this, PATH_OFFSET, path);
2337
UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path));
2338
}
2339
2340
private static final jdk.internal.misc.Unsafe UNSAFE
2341
= jdk.internal.misc.Unsafe.getUnsafe();
2342
private static final long PATH_OFFSET
2343
= UNSAFE.objectFieldOffset(File.class, "path");
2344
private static final long PREFIX_LENGTH_OFFSET
2345
= UNSAFE.objectFieldOffset(File.class, "prefixLength");
2346
2347
/** use serialVersionUID from JDK 1.0.2 for interoperability */
2348
@java.io.Serial
2349
private static final long serialVersionUID = 301077366599181567L;
2350
2351
// -- Integration with java.nio.file --
2352
2353
private transient volatile Path filePath;
2354
2355
/**
2356
* Returns a {@link Path java.nio.file.Path} object constructed from
2357
* this abstract path. The resulting {@code Path} is associated with the
2358
* {@link java.nio.file.FileSystems#getDefault default-filesystem}.
2359
*
2360
* <p> The first invocation of this method works as if invoking it were
2361
* equivalent to evaluating the expression:
2362
* <blockquote><pre>
2363
* {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link
2364
* java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}());
2365
* </pre></blockquote>
2366
* Subsequent invocations of this method return the same {@code Path}.
2367
*
2368
* <p> If this abstract pathname is the empty abstract pathname then this
2369
* method returns a {@code Path} that may be used to access the current
2370
* user directory.
2371
*
2372
* @return a {@code Path} constructed from this abstract path
2373
*
2374
* @throws java.nio.file.InvalidPathException
2375
* if a {@code Path} object cannot be constructed from the abstract
2376
* path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath})
2377
*
2378
* @since 1.7
2379
* @see Path#toFile
2380
*/
2381
public Path toPath() {
2382
Path result = filePath;
2383
if (result == null) {
2384
synchronized (this) {
2385
result = filePath;
2386
if (result == null) {
2387
result = FileSystems.getDefault().getPath(path);
2388
filePath = result;
2389
}
2390
}
2391
}
2392
return result;
2393
}
2394
}
2395
2396