Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/io/File.java
38829 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.util.List;
33
import java.util.ArrayList;
34
import java.security.AccessController;
35
import java.security.SecureRandom;
36
import java.nio.file.Path;
37
import java.nio.file.FileSystems;
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>"/"</code>&nbsp;for the UNIX root
51
* directory, or <code>"\\\\"</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</code>, and
66
* is made available in the public static fields <code>{@link
67
* #separator}</code> and <code>{@link #separatorChar}</code> 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</code> package always resolve relative pathnames against the
78
* current user directory. This directory is named by the system property
79
* <code>user.dir</code>, 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 <tt>File</tt>
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 <tt>"/usr"</tt> is an ancestor of the directory denoted by the
89
* pathname <tt>"/usr/local/bin"</tt>.
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>"/"</code>. Relative pathnames have no prefix. The abstract pathname
99
* denoting the root directory has the prefix <code>"/"</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>":"</code> and
104
* possibly followed by <code>"\\"</code> if the pathname is absolute. The
105
* prefix of a UNC pathname is <code>"\\\\"</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 name="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</code> class are immutable; that is, once
129
* created, the abstract pathname represented by a <code>File</code> object
130
* will never change.
131
*
132
* <h3>Interoperability with {@code java.nio.file} package</h3>
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
* @author unascribed
146
* @since JDK1.0
147
*/
148
149
public class File
150
implements Serializable, Comparable<File>
151
{
152
153
/**
154
* The FileSystem object representing the platform's local file system.
155
*/
156
private static final FileSystem fs = DefaultFileSystem.getFileSystem();
157
158
/**
159
* This abstract pathname's normalized pathname string. A normalized
160
* pathname string uses the default name-separator character and does not
161
* contain any duplicate or redundant separators.
162
*
163
* @serial
164
*/
165
private final String path;
166
167
/**
168
* Enum type that indicates the status of a file path.
169
*/
170
private static enum PathStatus { INVALID, CHECKED };
171
172
/**
173
* The flag indicating whether the file path is invalid.
174
*/
175
private transient PathStatus status = null;
176
177
/**
178
* Check if the file has an invalid path. Currently, the inspection of
179
* a file path is very limited, and it only covers Nul character check.
180
* Returning true means the path is definitely invalid/garbage. But
181
* returning false does not guarantee that the path is valid.
182
*
183
* @return true if the file path is invalid.
184
*/
185
final boolean isInvalid() {
186
PathStatus s = status;
187
if (s == null) {
188
s = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
189
: PathStatus.INVALID;
190
status = s;
191
}
192
return s == PathStatus.INVALID;
193
}
194
195
/**
196
* The length of this abstract pathname's prefix, or zero if it has no
197
* prefix.
198
*/
199
private final transient int prefixLength;
200
201
/**
202
* Returns the length of this abstract pathname's prefix.
203
* For use by FileSystem classes.
204
*/
205
int getPrefixLength() {
206
return prefixLength;
207
}
208
209
/**
210
* The system-dependent default name-separator character. This field is
211
* initialized to contain the first character of the value of the system
212
* property <code>file.separator</code>. On UNIX systems the value of this
213
* field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>.
214
*
215
* @see java.lang.System#getProperty(java.lang.String)
216
*/
217
public static final char separatorChar = fs.getSeparator();
218
219
/**
220
* The system-dependent default name-separator character, represented as a
221
* string for convenience. This string contains a single character, namely
222
* <code>{@link #separatorChar}</code>.
223
*/
224
public static final String separator = "" + separatorChar;
225
226
/**
227
* The system-dependent path-separator character. This field is
228
* initialized to contain the first character of the value of the system
229
* property <code>path.separator</code>. This character is used to
230
* separate filenames in a sequence of files given as a <em>path list</em>.
231
* On UNIX systems, this character is <code>':'</code>; on Microsoft Windows systems it
232
* is <code>';'</code>.
233
*
234
* @see java.lang.System#getProperty(java.lang.String)
235
*/
236
public static final char pathSeparatorChar = fs.getPathSeparator();
237
238
/**
239
* The system-dependent path-separator character, represented as a string
240
* for convenience. This string contains a single character, namely
241
* <code>{@link #pathSeparatorChar}</code>.
242
*/
243
public static final String pathSeparator = "" + pathSeparatorChar;
244
245
246
/* -- Constructors -- */
247
248
/**
249
* Internal constructor for already-normalized pathname strings.
250
*/
251
private File(String pathname, int prefixLength) {
252
this.path = pathname;
253
this.prefixLength = prefixLength;
254
}
255
256
/**
257
* Internal constructor for already-normalized pathname strings.
258
* The parameter order is used to disambiguate this method from the
259
* public(File, String) constructor.
260
*/
261
private File(String child, File parent) {
262
assert parent.path != null;
263
assert (!parent.path.equals(""));
264
this.path = fs.resolve(parent.path, child);
265
this.prefixLength = parent.prefixLength;
266
}
267
268
/**
269
* Creates a new <code>File</code> instance by converting the given
270
* pathname string into an abstract pathname. If the given string is
271
* the empty string, then the result is the empty abstract pathname.
272
*
273
* @param pathname A pathname string
274
* @throws NullPointerException
275
* If the <code>pathname</code> argument is <code>null</code>
276
*/
277
public File(String pathname) {
278
if (pathname == null) {
279
throw new NullPointerException();
280
}
281
this.path = fs.normalize(pathname);
282
this.prefixLength = fs.prefixLength(this.path);
283
}
284
285
/* Note: The two-argument File constructors do not interpret an empty
286
parent abstract pathname as the current user directory. An empty parent
287
instead causes the child to be resolved against the system-dependent
288
directory defined by the FileSystem.getDefaultParent method. On Unix
289
this default is "/", while on Microsoft Windows it is "\\". This is required for
290
compatibility with the original behavior of this class. */
291
292
/**
293
* Creates a new <code>File</code> instance from a parent pathname string
294
* and a child pathname string.
295
*
296
* <p> If <code>parent</code> is <code>null</code> then the new
297
* <code>File</code> instance is created as if by invoking the
298
* single-argument <code>File</code> constructor on the given
299
* <code>child</code> pathname string.
300
*
301
* <p> Otherwise the <code>parent</code> pathname string is taken to denote
302
* a directory, and the <code>child</code> pathname string is taken to
303
* denote either a directory or a file. If the <code>child</code> pathname
304
* string is absolute then it is converted into a relative pathname in a
305
* system-dependent way. If <code>parent</code> is the empty string then
306
* the new <code>File</code> instance is created by converting
307
* <code>child</code> into an abstract pathname and resolving the result
308
* against a system-dependent default directory. Otherwise each pathname
309
* string is converted into an abstract pathname and the child abstract
310
* pathname is resolved against the parent.
311
*
312
* @param parent The parent pathname string
313
* @param child The child pathname string
314
* @throws NullPointerException
315
* If <code>child</code> is <code>null</code>
316
*/
317
public File(String parent, String child) {
318
if (child == null) {
319
throw new NullPointerException();
320
}
321
if (parent != null) {
322
if (parent.equals("")) {
323
this.path = fs.resolve(fs.getDefaultParent(),
324
fs.normalize(child));
325
} else {
326
this.path = fs.resolve(fs.normalize(parent),
327
fs.normalize(child));
328
}
329
} else {
330
this.path = fs.normalize(child);
331
}
332
this.prefixLength = fs.prefixLength(this.path);
333
}
334
335
/**
336
* Creates a new <code>File</code> instance from a parent abstract
337
* pathname and a child pathname string.
338
*
339
* <p> If <code>parent</code> is <code>null</code> then the new
340
* <code>File</code> instance is created as if by invoking the
341
* single-argument <code>File</code> constructor on the given
342
* <code>child</code> pathname string.
343
*
344
* <p> Otherwise the <code>parent</code> abstract pathname is taken to
345
* denote a directory, and the <code>child</code> pathname string is taken
346
* to denote either a directory or a file. If the <code>child</code>
347
* pathname string is absolute then it is converted into a relative
348
* pathname in a system-dependent way. If <code>parent</code> is the empty
349
* abstract pathname then the new <code>File</code> instance is created by
350
* converting <code>child</code> into an abstract pathname and resolving
351
* the result against a system-dependent default directory. Otherwise each
352
* pathname string is converted into an abstract pathname and the child
353
* abstract pathname is resolved against the parent.
354
*
355
* @param parent The parent abstract pathname
356
* @param child The child pathname string
357
* @throws NullPointerException
358
* If <code>child</code> is <code>null</code>
359
*/
360
public File(File parent, String child) {
361
if (child == null) {
362
throw new NullPointerException();
363
}
364
if (parent != null) {
365
if (parent.path.equals("")) {
366
this.path = fs.resolve(fs.getDefaultParent(),
367
fs.normalize(child));
368
} else {
369
this.path = fs.resolve(parent.path,
370
fs.normalize(child));
371
}
372
} else {
373
this.path = fs.normalize(child);
374
}
375
this.prefixLength = fs.prefixLength(this.path);
376
}
377
378
/**
379
* Creates a new <tt>File</tt> instance by converting the given
380
* <tt>file:</tt> URI into an abstract pathname.
381
*
382
* <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence
383
* the transformation performed by this constructor is also
384
* system-dependent.
385
*
386
* <p> For a given abstract pathname <i>f</i> it is guaranteed that
387
*
388
* <blockquote><tt>
389
* new File(</tt><i>&nbsp;f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i>&nbsp;f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
390
* </tt></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 <tt>file:</tt> 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
* <tt>"file"</tt>, a non-empty path component, and undefined
402
* authority, query, and fragment components
403
*
404
* @throws NullPointerException
405
* If <tt>uri</tt> is <tt>null</tt>
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.getAuthority() != null)
425
throw new IllegalArgumentException("URI has an authority component");
426
if (uri.getFragment() != null)
427
throw new IllegalArgumentException("URI has a fragment component");
428
if (uri.getQuery() != null)
429
throw new IllegalArgumentException("URI has a query component");
430
String p = uri.getPath();
431
if (p.equals(""))
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</code> 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</code> 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</code> 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</code> 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>"/"</code>. On Microsoft Windows systems, a
527
* pathname is absolute if its prefix is a drive specifier followed by
528
* <code>"\\"</code>, or if its prefix is <code>"\\\\"</code>.
529
*
530
* @return <code>true</code> if this abstract pathname is absolute,
531
* <code>false</code> 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 <code>{@link #getPath}</code>
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</code>, 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 <tt>"."</tt> and <tt>".."</tt> 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 <code>{@link
616
* java.lang.SecurityManager#checkRead}</code> method denies
617
* read access to the file
618
*
619
* @since JDK1.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 <code>{@link
644
* java.lang.SecurityManager#checkRead}</code> 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:</code> 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 <tt>file:</tt> 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><tt>
710
* new {@link #File(java.net.URI) File}(</tt><i>&nbsp;f</i><tt>.toURI()).equals(</tt><i>&nbsp;f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
711
* </tt></blockquote>
712
*
713
* so long as the original abstract pathname, the URI, and the new abstract
714
* pathname are all created in (possibly different invocations of) the same
715
* Java virtual machine. Due to the system-dependent nature of abstract
716
* pathnames, however, this relationship typically does not hold when a
717
* <tt>file:</tt> URI that is created in a virtual machine on one operating
718
* system is converted into an abstract pathname in a virtual machine on a
719
* different operating system.
720
*
721
* <p> Note that when this abstract pathname represents a UNC pathname then
722
* all components of the UNC (including the server name component) are encoded
723
* in the {@code URI} path. The authority component is undefined, meaning
724
* that it is represented as {@code null}. The {@link Path} class defines the
725
* {@link Path#toUri toUri} method to encode the server name in the authority
726
* component of the resulting {@code URI}. The {@link #toPath toPath} method
727
* may be used to obtain a {@code Path} representing this abstract pathname.
728
*
729
* @return An absolute, hierarchical URI with a scheme equal to
730
* <tt>"file"</tt>, a path representing this abstract pathname,
731
* and undefined authority, query, and fragment components
732
* @throws SecurityException If a required system property value cannot
733
* be accessed.
734
*
735
* @see #File(java.net.URI)
736
* @see java.net.URI
737
* @see java.net.URI#toURL()
738
* @since 1.4
739
*/
740
public URI toURI() {
741
try {
742
File f = getAbsoluteFile();
743
String sp = slashify(f.getPath(), f.isDirectory());
744
if (sp.startsWith("//"))
745
sp = "//" + sp;
746
return new URI("file", null, sp, null);
747
} catch (URISyntaxException x) {
748
throw new Error(x); // Can't happen
749
}
750
}
751
752
753
/* -- Attribute accessors -- */
754
755
/**
756
* Tests whether the application can read the file denoted by this
757
* abstract pathname. On some platforms it may be possible to start the
758
* Java virtual machine with special privileges that allow it to read
759
* files that are marked as unreadable. Consequently this method may return
760
* {@code true} even though the file does not have read permissions.
761
*
762
* @return <code>true</code> if and only if the file specified by this
763
* abstract pathname exists <em>and</em> can be read by the
764
* application; <code>false</code> otherwise
765
*
766
* @throws SecurityException
767
* If a security manager exists and its <code>{@link
768
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
769
* method denies read access to the file
770
*/
771
public boolean canRead() {
772
SecurityManager security = System.getSecurityManager();
773
if (security != null) {
774
security.checkRead(path);
775
}
776
if (isInvalid()) {
777
return false;
778
}
779
return fs.checkAccess(this, FileSystem.ACCESS_READ);
780
}
781
782
/**
783
* Tests whether the application can modify the file denoted by this
784
* abstract pathname. On some platforms it may be possible to start the
785
* Java virtual machine with special privileges that allow it to modify
786
* files that are marked read-only. Consequently this method may return
787
* {@code true} even though the file is marked read-only.
788
*
789
* @return <code>true</code> if and only if the file system actually
790
* contains a file denoted by this abstract pathname <em>and</em>
791
* the application is allowed to write to the file;
792
* <code>false</code> otherwise.
793
*
794
* @throws SecurityException
795
* If a security manager exists and its <code>{@link
796
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
797
* method denies write access to the file
798
*/
799
public boolean canWrite() {
800
SecurityManager security = System.getSecurityManager();
801
if (security != null) {
802
security.checkWrite(path);
803
}
804
if (isInvalid()) {
805
return false;
806
}
807
return fs.checkAccess(this, FileSystem.ACCESS_WRITE);
808
}
809
810
/**
811
* Tests whether the file or directory denoted by this abstract pathname
812
* exists.
813
*
814
* @return <code>true</code> if and only if the file or directory denoted
815
* by this abstract pathname exists; <code>false</code> otherwise
816
*
817
* @throws SecurityException
818
* If a security manager exists and its <code>{@link
819
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
820
* method denies read access to the file or directory
821
*/
822
public boolean exists() {
823
SecurityManager security = System.getSecurityManager();
824
if (security != null) {
825
security.checkRead(path);
826
}
827
if (isInvalid()) {
828
return false;
829
}
830
return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0);
831
}
832
833
/**
834
* Tests whether the file denoted by this abstract pathname is a
835
* directory.
836
*
837
* <p> Where it is required to distinguish an I/O exception from the case
838
* that the file is not a directory, or where several attributes of the
839
* same file are required at the same time, then the {@link
840
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
841
* Files.readAttributes} method may be used.
842
*
843
* @return <code>true</code> if and only if the file denoted by this
844
* abstract pathname exists <em>and</em> is a directory;
845
* <code>false</code> otherwise
846
*
847
* @throws SecurityException
848
* If a security manager exists and its <code>{@link
849
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
850
* method denies read access to the file
851
*/
852
public boolean isDirectory() {
853
SecurityManager security = System.getSecurityManager();
854
if (security != null) {
855
security.checkRead(path);
856
}
857
if (isInvalid()) {
858
return false;
859
}
860
return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)
861
!= 0);
862
}
863
864
/**
865
* Tests whether the file denoted by this abstract pathname is a normal
866
* file. A file is <em>normal</em> if it is not a directory and, in
867
* addition, satisfies other system-dependent criteria. Any non-directory
868
* file created by a Java application is guaranteed to be a normal file.
869
*
870
* <p> Where it is required to distinguish an I/O exception from the case
871
* that the file is not a normal file, or where several attributes of the
872
* same file are required at the same time, then the {@link
873
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
874
* Files.readAttributes} method may be used.
875
*
876
* @return <code>true</code> if and only if the file denoted by this
877
* abstract pathname exists <em>and</em> is a normal file;
878
* <code>false</code> otherwise
879
*
880
* @throws SecurityException
881
* If a security manager exists and its <code>{@link
882
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
883
* method denies read access to the file
884
*/
885
public boolean isFile() {
886
SecurityManager security = System.getSecurityManager();
887
if (security != null) {
888
security.checkRead(path);
889
}
890
if (isInvalid()) {
891
return false;
892
}
893
return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);
894
}
895
896
/**
897
* Tests whether the file named by this abstract pathname is a hidden
898
* file. The exact definition of <em>hidden</em> is system-dependent. On
899
* UNIX systems, a file is considered to be hidden if its name begins with
900
* a period character (<code>'.'</code>). On Microsoft Windows systems, a file is
901
* considered to be hidden if it has been marked as such in the filesystem.
902
*
903
* @return <code>true</code> if and only if the file denoted by this
904
* abstract pathname is hidden according to the conventions of the
905
* underlying platform
906
*
907
* @throws SecurityException
908
* If a security manager exists and its <code>{@link
909
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
910
* method denies read access to the file
911
*
912
* @since 1.2
913
*/
914
public boolean isHidden() {
915
SecurityManager security = System.getSecurityManager();
916
if (security != null) {
917
security.checkRead(path);
918
}
919
if (isInvalid()) {
920
return false;
921
}
922
return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0);
923
}
924
925
/**
926
* Returns the time that the file denoted by this abstract pathname was
927
* last modified.
928
*
929
* <p> Where it is required to distinguish an I/O exception from the case
930
* where {@code 0L} is returned, or where several attributes of the
931
* same file are required at the same time, or where the time of last
932
* access or the creation time are required, then the {@link
933
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
934
* Files.readAttributes} method may be used.
935
*
936
* @return A <code>long</code> value representing the time the file was
937
* last modified, measured in milliseconds since the epoch
938
* (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the
939
* file does not exist or if an I/O error occurs
940
*
941
* @throws SecurityException
942
* If a security manager exists and its <code>{@link
943
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
944
* method denies read access to the file
945
*/
946
public long lastModified() {
947
SecurityManager security = System.getSecurityManager();
948
if (security != null) {
949
security.checkRead(path);
950
}
951
if (isInvalid()) {
952
return 0L;
953
}
954
return fs.getLastModifiedTime(this);
955
}
956
957
/**
958
* Returns the length of the file denoted by this abstract pathname.
959
* The return value is unspecified if this pathname denotes a directory.
960
*
961
* <p> Where it is required to distinguish an I/O exception from the case
962
* that {@code 0L} is returned, or where several attributes of the same file
963
* are required at the same time, then the {@link
964
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
965
* Files.readAttributes} method may be used.
966
*
967
* @return The length, in bytes, of the file denoted by this abstract
968
* pathname, or <code>0L</code> if the file does not exist. Some
969
* operating systems may return <code>0L</code> for pathnames
970
* denoting system-dependent entities such as devices or pipes.
971
*
972
* @throws SecurityException
973
* If a security manager exists and its <code>{@link
974
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
975
* method denies read access to the file
976
*/
977
public long length() {
978
SecurityManager security = System.getSecurityManager();
979
if (security != null) {
980
security.checkRead(path);
981
}
982
if (isInvalid()) {
983
return 0L;
984
}
985
return fs.getLength(this);
986
}
987
988
989
/* -- File operations -- */
990
991
/**
992
* Atomically creates a new, empty file named by this abstract pathname if
993
* and only if a file with this name does not yet exist. The check for the
994
* existence of the file and the creation of the file if it does not exist
995
* are a single operation that is atomic with respect to all other
996
* filesystem activities that might affect the file.
997
* <P>
998
* Note: this method should <i>not</i> be used for file-locking, as
999
* the resulting protocol cannot be made to work reliably. The
1000
* {@link java.nio.channels.FileLock FileLock}
1001
* facility should be used instead.
1002
*
1003
* @return <code>true</code> if the named file does not exist and was
1004
* successfully created; <code>false</code> if the named file
1005
* already exists
1006
*
1007
* @throws IOException
1008
* If an I/O error occurred
1009
*
1010
* @throws SecurityException
1011
* If a security manager exists and its <code>{@link
1012
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1013
* method denies write access to the file
1014
*
1015
* @since 1.2
1016
*/
1017
public boolean createNewFile() throws IOException {
1018
SecurityManager security = System.getSecurityManager();
1019
if (security != null) security.checkWrite(path);
1020
if (isInvalid()) {
1021
throw new IOException("Invalid file path");
1022
}
1023
return fs.createFileExclusively(path);
1024
}
1025
1026
/**
1027
* Deletes the file or directory denoted by this abstract pathname. If
1028
* this pathname denotes a directory, then the directory must be empty in
1029
* order to be deleted.
1030
*
1031
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1032
* java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}
1033
* when a file cannot be deleted. This is useful for error reporting and to
1034
* diagnose why a file cannot be deleted.
1035
*
1036
* @return <code>true</code> if and only if the file or directory is
1037
* successfully deleted; <code>false</code> otherwise
1038
*
1039
* @throws SecurityException
1040
* If a security manager exists and its <code>{@link
1041
* java.lang.SecurityManager#checkDelete}</code> method denies
1042
* delete access to the file
1043
*/
1044
public boolean delete() {
1045
SecurityManager security = System.getSecurityManager();
1046
if (security != null) {
1047
security.checkDelete(path);
1048
}
1049
if (isInvalid()) {
1050
return false;
1051
}
1052
return fs.delete(this);
1053
}
1054
1055
/**
1056
* Requests that the file or directory denoted by this abstract
1057
* pathname be deleted when the virtual machine terminates.
1058
* Files (or directories) are deleted in the reverse order that
1059
* they are registered. Invoking this method to delete a file or
1060
* directory that is already registered for deletion has no effect.
1061
* Deletion will be attempted only for normal termination of the
1062
* virtual machine, as defined by the Java Language Specification.
1063
*
1064
* <p> Once deletion has been requested, it is not possible to cancel the
1065
* request. This method should therefore be used with care.
1066
*
1067
* <P>
1068
* Note: this method should <i>not</i> be used for file-locking, as
1069
* the resulting protocol cannot be made to work reliably. The
1070
* {@link java.nio.channels.FileLock FileLock}
1071
* facility should be used instead.
1072
*
1073
* @throws SecurityException
1074
* If a security manager exists and its <code>{@link
1075
* java.lang.SecurityManager#checkDelete}</code> method denies
1076
* delete access to the file
1077
*
1078
* @see #delete
1079
*
1080
* @since 1.2
1081
*/
1082
public void deleteOnExit() {
1083
SecurityManager security = System.getSecurityManager();
1084
if (security != null) {
1085
security.checkDelete(path);
1086
}
1087
if (isInvalid()) {
1088
return;
1089
}
1090
DeleteOnExitHook.add(path);
1091
}
1092
1093
/**
1094
* Returns an array of strings naming the files and directories in the
1095
* directory denoted by this abstract pathname.
1096
*
1097
* <p> If this abstract pathname does not denote a directory, then this
1098
* method returns {@code null}. Otherwise an array of strings is
1099
* returned, one for each file or directory in the directory. Names
1100
* denoting the directory itself and the directory's parent directory are
1101
* not included in the result. Each string is a file name rather than a
1102
* complete path.
1103
*
1104
* <p> There is no guarantee that the name strings in the resulting array
1105
* will appear in any specific order; they are not, in particular,
1106
* guaranteed to appear in alphabetical order.
1107
*
1108
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1109
* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method to
1110
* open a directory and iterate over the names of the files in the directory.
1111
* This may use less resources when working with very large directories, and
1112
* may be more responsive when working with remote directories.
1113
*
1114
* @return An array of strings naming the files and directories in the
1115
* directory denoted by this abstract pathname. The array will be
1116
* empty if the directory is empty. Returns {@code null} if
1117
* this abstract pathname does not denote a directory, or if an
1118
* I/O error occurs.
1119
*
1120
* @throws SecurityException
1121
* If a security manager exists and its {@link
1122
* SecurityManager#checkRead(String)} method denies read access to
1123
* the directory
1124
*/
1125
public String[] list() {
1126
return normalizedList();
1127
}
1128
1129
/**
1130
* Returns an array of strings naming the files and directories in the
1131
* directory denoted by this abstract pathname. The strings are
1132
* ensured to represent normalized paths.
1133
*
1134
* @return An array of strings naming the files and directories in the
1135
* directory denoted by this abstract pathname. The array will be
1136
* empty if the directory is empty. Returns {@code null} if
1137
* this abstract pathname does not denote a directory, or if an
1138
* I/O error occurs.
1139
*
1140
* @throws SecurityException
1141
* If a security manager exists and its {@link
1142
* SecurityManager#checkRead(String)} method denies read access to
1143
* the directory
1144
*/
1145
private final String[] normalizedList() {
1146
SecurityManager security = System.getSecurityManager();
1147
if (security != null) {
1148
security.checkRead(path);
1149
}
1150
if (isInvalid()) {
1151
return null;
1152
}
1153
String[] s = fs.list(this);
1154
if (s != null && getClass() != File.class) {
1155
String[] normalized = new String[s.length];
1156
for (int i = 0; i < s.length; i++) {
1157
normalized[i] = fs.normalize(s[i]);
1158
}
1159
s = normalized;
1160
}
1161
return s;
1162
}
1163
1164
/**
1165
* Returns an array of strings naming the files and directories in the
1166
* directory denoted by this abstract pathname that satisfy the specified
1167
* filter. The behavior of this method is the same as that of the
1168
* {@link #list()} method, except that the strings in the returned array
1169
* must satisfy the filter. If the given {@code filter} is {@code null}
1170
* then all names are accepted. Otherwise, a name satisfies the filter if
1171
* and only if the value {@code true} results when the {@link
1172
* FilenameFilter#accept FilenameFilter.accept(File,&nbsp;String)} method
1173
* of the filter is invoked on this abstract pathname and the name of a
1174
* file or directory in the directory that it denotes.
1175
*
1176
* @param filter
1177
* A filename filter
1178
*
1179
* @return An array of strings naming the files and directories in the
1180
* directory denoted by this abstract pathname that were accepted
1181
* by the given {@code filter}. The array will be empty if the
1182
* directory is empty or if no names were accepted by the filter.
1183
* Returns {@code null} if this abstract pathname does not denote
1184
* a directory, or if an I/O error occurs.
1185
*
1186
* @throws SecurityException
1187
* If a security manager exists and its {@link
1188
* SecurityManager#checkRead(String)} method denies read access to
1189
* the directory
1190
*
1191
* @see java.nio.file.Files#newDirectoryStream(Path,String)
1192
*/
1193
public String[] list(FilenameFilter filter) {
1194
String names[] = normalizedList();
1195
if ((names == null) || (filter == null)) {
1196
return names;
1197
}
1198
List<String> v = new ArrayList<>();
1199
for (int i = 0 ; i < names.length ; i++) {
1200
if (filter.accept(this, names[i])) {
1201
v.add(names[i]);
1202
}
1203
}
1204
return v.toArray(new String[v.size()]);
1205
}
1206
1207
/**
1208
* Returns an array of abstract pathnames denoting the files in the
1209
* directory denoted by this abstract pathname.
1210
*
1211
* <p> If this abstract pathname does not denote a directory, then this
1212
* method returns {@code null}. Otherwise an array of {@code File} objects
1213
* is returned, one for each file or directory in the directory. Pathnames
1214
* denoting the directory itself and the directory's parent directory are
1215
* not included in the result. Each resulting abstract pathname is
1216
* constructed from this abstract pathname using the {@link #File(File,
1217
* String) File(File,&nbsp;String)} constructor. Therefore if this
1218
* pathname is absolute then each resulting pathname is absolute; if this
1219
* pathname is relative then each resulting pathname will be relative to
1220
* the same directory.
1221
*
1222
* <p> There is no guarantee that the name strings in the resulting array
1223
* will appear in any specific order; they are not, in particular,
1224
* guaranteed to appear in alphabetical order.
1225
*
1226
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1227
* java.nio.file.Files#newDirectoryStream(Path) newDirectoryStream} method
1228
* to open a directory and iterate over the names of the files in the
1229
* directory. This may use less resources when working with very large
1230
* directories.
1231
*
1232
* @return An array of abstract pathnames denoting the files and
1233
* directories in the directory denoted by this abstract pathname.
1234
* The array will be empty if the directory is empty. Returns
1235
* {@code null} if this abstract pathname does not denote a
1236
* directory, or if an I/O error occurs.
1237
*
1238
* @throws SecurityException
1239
* If a security manager exists and its {@link
1240
* SecurityManager#checkRead(String)} method denies read access to
1241
* the directory
1242
*
1243
* @since 1.2
1244
*/
1245
public File[] listFiles() {
1246
String[] ss = normalizedList();
1247
if (ss == null) return null;
1248
int n = ss.length;
1249
File[] fs = new File[n];
1250
for (int i = 0; i < n; i++) {
1251
fs[i] = new File(ss[i], this);
1252
}
1253
return fs;
1254
}
1255
1256
/**
1257
* Returns an array of abstract pathnames denoting the files and
1258
* directories in the directory denoted by this abstract pathname that
1259
* satisfy the specified filter. The behavior of this method is the same
1260
* as that of the {@link #listFiles()} method, except that the pathnames in
1261
* the returned array must satisfy the filter. If the given {@code filter}
1262
* is {@code null} then all pathnames are accepted. Otherwise, a pathname
1263
* satisfies the filter if and only if the value {@code true} results when
1264
* the {@link FilenameFilter#accept
1265
* FilenameFilter.accept(File,&nbsp;String)} method of the filter is
1266
* invoked on this abstract pathname and the name of a file or directory in
1267
* the directory that it denotes.
1268
*
1269
* @param filter
1270
* A filename filter
1271
*
1272
* @return An array of abstract pathnames denoting the files and
1273
* directories in the directory denoted by this abstract pathname.
1274
* The array will be empty if the directory is empty. Returns
1275
* {@code null} if this abstract pathname does not denote a
1276
* directory, or if an I/O error occurs.
1277
*
1278
* @throws SecurityException
1279
* If a security manager exists and its {@link
1280
* SecurityManager#checkRead(String)} method denies read access to
1281
* the directory
1282
*
1283
* @since 1.2
1284
* @see java.nio.file.Files#newDirectoryStream(Path,String)
1285
*/
1286
public File[] listFiles(FilenameFilter filter) {
1287
String ss[] = normalizedList();
1288
if (ss == null) return null;
1289
ArrayList<File> files = new ArrayList<>();
1290
for (String s : ss)
1291
if ((filter == null) || filter.accept(this, s))
1292
files.add(new File(s, this));
1293
return files.toArray(new File[files.size()]);
1294
}
1295
1296
/**
1297
* Returns an array of abstract pathnames denoting the files and
1298
* directories in the directory denoted by this abstract pathname that
1299
* satisfy the specified filter. The behavior of this method is the same
1300
* as that of the {@link #listFiles()} method, except that the pathnames in
1301
* the returned array must satisfy the filter. If the given {@code filter}
1302
* is {@code null} then all pathnames are accepted. Otherwise, a pathname
1303
* satisfies the filter if and only if the value {@code true} results when
1304
* the {@link FileFilter#accept FileFilter.accept(File)} method of the
1305
* filter is invoked on the pathname.
1306
*
1307
* @param filter
1308
* A file filter
1309
*
1310
* @return An array of abstract pathnames denoting the files and
1311
* directories in the directory denoted by this abstract pathname.
1312
* The array will be empty if the directory is empty. Returns
1313
* {@code null} if this abstract pathname does not denote a
1314
* directory, or if an I/O error occurs.
1315
*
1316
* @throws SecurityException
1317
* If a security manager exists and its {@link
1318
* SecurityManager#checkRead(String)} method denies read access to
1319
* the directory
1320
*
1321
* @since 1.2
1322
* @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter)
1323
*/
1324
public File[] listFiles(FileFilter filter) {
1325
String ss[] = normalizedList();
1326
if (ss == null) return null;
1327
ArrayList<File> files = new ArrayList<>();
1328
for (String s : ss) {
1329
File f = new File(s, this);
1330
if ((filter == null) || filter.accept(f))
1331
files.add(f);
1332
}
1333
return files.toArray(new File[files.size()]);
1334
}
1335
1336
/**
1337
* Creates the directory named by this abstract pathname.
1338
*
1339
* @return <code>true</code> if and only if the directory was
1340
* created; <code>false</code> otherwise
1341
*
1342
* @throws SecurityException
1343
* If a security manager exists and its <code>{@link
1344
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1345
* method does not permit the named directory to be created
1346
*/
1347
public boolean mkdir() {
1348
SecurityManager security = System.getSecurityManager();
1349
if (security != null) {
1350
security.checkWrite(path);
1351
}
1352
if (isInvalid()) {
1353
return false;
1354
}
1355
return fs.createDirectory(this);
1356
}
1357
1358
/**
1359
* Creates the directory named by this abstract pathname, including any
1360
* necessary but nonexistent parent directories. Note that if this
1361
* operation fails it may have succeeded in creating some of the necessary
1362
* parent directories.
1363
*
1364
* @return <code>true</code> if and only if the directory was created,
1365
* along with all necessary parent directories; <code>false</code>
1366
* otherwise
1367
*
1368
* @throws SecurityException
1369
* If a security manager exists and its <code>{@link
1370
* java.lang.SecurityManager#checkRead(java.lang.String)}</code>
1371
* method does not permit verification of the existence of the
1372
* named directory and all necessary parent directories; or if
1373
* the <code>{@link
1374
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1375
* method does not permit the named directory and all necessary
1376
* parent directories to be created
1377
*/
1378
public boolean mkdirs() {
1379
if (exists()) {
1380
return false;
1381
}
1382
if (mkdir()) {
1383
return true;
1384
}
1385
File canonFile = null;
1386
try {
1387
canonFile = getCanonicalFile();
1388
} catch (IOException e) {
1389
return false;
1390
}
1391
1392
File parent = canonFile.getParentFile();
1393
return (parent != null && (parent.mkdirs() || parent.exists()) &&
1394
canonFile.mkdir());
1395
}
1396
1397
/**
1398
* Renames the file denoted by this abstract pathname.
1399
*
1400
* <p> Many aspects of the behavior of this method are inherently
1401
* platform-dependent: The rename operation might not be able to move a
1402
* file from one filesystem to another, it might not be atomic, and it
1403
* might not succeed if a file with the destination abstract pathname
1404
* already exists. The return value should always be checked to make sure
1405
* that the rename operation was successful.
1406
*
1407
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
1408
* java.nio.file.Files#move move} method to move or rename a file in a
1409
* platform independent manner.
1410
*
1411
* @param dest The new abstract pathname for the named file
1412
*
1413
* @return <code>true</code> if and only if the renaming succeeded;
1414
* <code>false</code> otherwise
1415
*
1416
* @throws SecurityException
1417
* If a security manager exists and its <code>{@link
1418
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1419
* method denies write access to either the old or new pathnames
1420
*
1421
* @throws NullPointerException
1422
* If parameter <code>dest</code> is <code>null</code>
1423
*/
1424
public boolean renameTo(File dest) {
1425
SecurityManager security = System.getSecurityManager();
1426
if (security != null) {
1427
security.checkWrite(path);
1428
security.checkWrite(dest.path);
1429
}
1430
if (dest == null) {
1431
throw new NullPointerException();
1432
}
1433
if (this.isInvalid() || dest.isInvalid()) {
1434
return false;
1435
}
1436
return fs.rename(this, dest);
1437
}
1438
1439
/**
1440
* Sets the last-modified time of the file or directory named by this
1441
* abstract pathname.
1442
*
1443
* <p> All platforms support file-modification times to the nearest second,
1444
* but some provide more precision. The argument will be truncated to fit
1445
* the supported precision. If the operation succeeds and no intervening
1446
* operations on the file take place, then the next invocation of the
1447
* <code>{@link #lastModified}</code> method will return the (possibly
1448
* truncated) <code>time</code> argument that was passed to this method.
1449
*
1450
* @param time The new last-modified time, measured in milliseconds since
1451
* the epoch (00:00:00 GMT, January 1, 1970)
1452
*
1453
* @return <code>true</code> if and only if the operation succeeded;
1454
* <code>false</code> otherwise
1455
*
1456
* @throws IllegalArgumentException If the argument is negative
1457
*
1458
* @throws SecurityException
1459
* If a security manager exists and its <code>{@link
1460
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1461
* method denies write access to the named file
1462
*
1463
* @since 1.2
1464
*/
1465
public boolean setLastModified(long time) {
1466
if (time < 0) throw new IllegalArgumentException("Negative time");
1467
SecurityManager security = System.getSecurityManager();
1468
if (security != null) {
1469
security.checkWrite(path);
1470
}
1471
if (isInvalid()) {
1472
return false;
1473
}
1474
return fs.setLastModifiedTime(this, time);
1475
}
1476
1477
/**
1478
* Marks the file or directory named by this abstract pathname so that
1479
* only read operations are allowed. After invoking this method the file
1480
* or directory will not change until it is either deleted or marked
1481
* to allow write access. On some platforms it may be possible to start the
1482
* Java virtual machine with special privileges that allow it to modify
1483
* files that are marked read-only. Whether or not a read-only file or
1484
* directory may be deleted depends upon the underlying system.
1485
*
1486
* @return <code>true</code> if and only if the operation succeeded;
1487
* <code>false</code> otherwise
1488
*
1489
* @throws SecurityException
1490
* If a security manager exists and its <code>{@link
1491
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1492
* method denies write access to the named file
1493
*
1494
* @since 1.2
1495
*/
1496
public boolean setReadOnly() {
1497
SecurityManager security = System.getSecurityManager();
1498
if (security != null) {
1499
security.checkWrite(path);
1500
}
1501
if (isInvalid()) {
1502
return false;
1503
}
1504
return fs.setReadOnly(this);
1505
}
1506
1507
/**
1508
* Sets the owner's or everybody's write permission for this abstract
1509
* pathname. On some platforms it may be possible to start the Java virtual
1510
* machine with special privileges that allow it to modify files that
1511
* disallow write operations.
1512
*
1513
* <p> The {@link java.nio.file.Files} class defines methods that operate on
1514
* file attributes including file permissions. This may be used when finer
1515
* manipulation of file permissions is required.
1516
*
1517
* @param writable
1518
* If <code>true</code>, sets the access permission to allow write
1519
* operations; if <code>false</code> to disallow write operations
1520
*
1521
* @param ownerOnly
1522
* If <code>true</code>, the write permission applies only to the
1523
* owner's write permission; otherwise, it applies to everybody. If
1524
* the underlying file system can not distinguish the owner's write
1525
* permission from that of others, then the permission will apply to
1526
* everybody, regardless of this value.
1527
*
1528
* @return <code>true</code> if and only if the operation succeeded. The
1529
* operation will fail if the user does not have permission to change
1530
* the access permissions of this abstract pathname.
1531
*
1532
* @throws SecurityException
1533
* If a security manager exists and its <code>{@link
1534
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1535
* method denies write access to the named file
1536
*
1537
* @since 1.6
1538
*/
1539
public boolean setWritable(boolean writable, boolean ownerOnly) {
1540
SecurityManager security = System.getSecurityManager();
1541
if (security != null) {
1542
security.checkWrite(path);
1543
}
1544
if (isInvalid()) {
1545
return false;
1546
}
1547
return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly);
1548
}
1549
1550
/**
1551
* A convenience method to set the owner's write permission for this abstract
1552
* pathname. On some platforms it may be possible to start the Java virtual
1553
* machine with special privileges that allow it to modify files that
1554
* disallow write operations.
1555
*
1556
* <p> An invocation of this method of the form <tt>file.setWritable(arg)</tt>
1557
* behaves in exactly the same way as the invocation
1558
*
1559
* <pre>
1560
* file.setWritable(arg, true) </pre>
1561
*
1562
* @param writable
1563
* If <code>true</code>, sets the access permission to allow write
1564
* operations; if <code>false</code> to disallow write operations
1565
*
1566
* @return <code>true</code> if and only if the operation succeeded. The
1567
* operation will fail if the user does not have permission to
1568
* change the access permissions of this abstract pathname.
1569
*
1570
* @throws SecurityException
1571
* If a security manager exists and its <code>{@link
1572
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1573
* method denies write access to the file
1574
*
1575
* @since 1.6
1576
*/
1577
public boolean setWritable(boolean writable) {
1578
return setWritable(writable, true);
1579
}
1580
1581
/**
1582
* Sets the owner's or everybody's read permission for this abstract
1583
* pathname. On some platforms it may be possible to start the Java virtual
1584
* machine with special privileges that allow it to read files that are
1585
* marked as unreadable.
1586
*
1587
* <p> The {@link java.nio.file.Files} class defines methods that operate on
1588
* file attributes including file permissions. This may be used when finer
1589
* manipulation of file permissions is required.
1590
*
1591
* @param readable
1592
* If <code>true</code>, sets the access permission to allow read
1593
* operations; if <code>false</code> to disallow read operations
1594
*
1595
* @param ownerOnly
1596
* If <code>true</code>, the read permission applies only to the
1597
* owner's read permission; otherwise, it applies to everybody. If
1598
* the underlying file system can not distinguish the owner's read
1599
* permission from that of others, then the permission will apply to
1600
* everybody, regardless of this value.
1601
*
1602
* @return <code>true</code> if and only if the operation succeeded. The
1603
* operation will fail if the user does not have permission to
1604
* change the access permissions of this abstract pathname. If
1605
* <code>readable</code> is <code>false</code> and the underlying
1606
* file system does not implement a read permission, then the
1607
* operation will fail.
1608
*
1609
* @throws SecurityException
1610
* If a security manager exists and its <code>{@link
1611
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1612
* method denies write access to the file
1613
*
1614
* @since 1.6
1615
*/
1616
public boolean setReadable(boolean readable, boolean ownerOnly) {
1617
SecurityManager security = System.getSecurityManager();
1618
if (security != null) {
1619
security.checkWrite(path);
1620
}
1621
if (isInvalid()) {
1622
return false;
1623
}
1624
return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly);
1625
}
1626
1627
/**
1628
* A convenience method to set the owner's read permission for this abstract
1629
* pathname. On some platforms it may be possible to start the Java virtual
1630
* machine with special privileges that allow it to read files that that are
1631
* marked as unreadable.
1632
*
1633
* <p>An invocation of this method of the form <tt>file.setReadable(arg)</tt>
1634
* behaves in exactly the same way as the invocation
1635
*
1636
* <pre>
1637
* file.setReadable(arg, true) </pre>
1638
*
1639
* @param readable
1640
* If <code>true</code>, sets the access permission to allow read
1641
* operations; if <code>false</code> to disallow read operations
1642
*
1643
* @return <code>true</code> if and only if the operation succeeded. The
1644
* operation will fail if the user does not have permission to
1645
* change the access permissions of this abstract pathname. If
1646
* <code>readable</code> is <code>false</code> and the underlying
1647
* file system does not implement a read permission, then the
1648
* operation will fail.
1649
*
1650
* @throws SecurityException
1651
* If a security manager exists and its <code>{@link
1652
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1653
* method denies write access to the file
1654
*
1655
* @since 1.6
1656
*/
1657
public boolean setReadable(boolean readable) {
1658
return setReadable(readable, true);
1659
}
1660
1661
/**
1662
* Sets the owner's or everybody's execute permission for this abstract
1663
* pathname. On some platforms it may be possible to start the Java virtual
1664
* machine with special privileges that allow it to execute files that are
1665
* not marked executable.
1666
*
1667
* <p> The {@link java.nio.file.Files} class defines methods that operate on
1668
* file attributes including file permissions. This may be used when finer
1669
* manipulation of file permissions is required.
1670
*
1671
* @param executable
1672
* If <code>true</code>, sets the access permission to allow execute
1673
* operations; if <code>false</code> to disallow execute operations
1674
*
1675
* @param ownerOnly
1676
* If <code>true</code>, the execute permission applies only to the
1677
* owner's execute permission; otherwise, it applies to everybody.
1678
* If the underlying file system can not distinguish the owner's
1679
* execute permission from that of others, then the permission will
1680
* apply to everybody, regardless of this value.
1681
*
1682
* @return <code>true</code> if and only if the operation succeeded. The
1683
* operation will fail if the user does not have permission to
1684
* change the access permissions of this abstract pathname. If
1685
* <code>executable</code> is <code>false</code> and the underlying
1686
* file system does not implement an execute permission, then the
1687
* operation will fail.
1688
*
1689
* @throws SecurityException
1690
* If a security manager exists and its <code>{@link
1691
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1692
* method denies write access to the file
1693
*
1694
* @since 1.6
1695
*/
1696
public boolean setExecutable(boolean executable, boolean ownerOnly) {
1697
SecurityManager security = System.getSecurityManager();
1698
if (security != null) {
1699
security.checkWrite(path);
1700
}
1701
if (isInvalid()) {
1702
return false;
1703
}
1704
return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly);
1705
}
1706
1707
/**
1708
* A convenience method to set the owner's execute permission for this
1709
* abstract pathname. On some platforms it may be possible to start the Java
1710
* virtual machine with special privileges that allow it to execute files
1711
* that are not marked executable.
1712
*
1713
* <p>An invocation of this method of the form <tt>file.setExcutable(arg)</tt>
1714
* behaves in exactly the same way as the invocation
1715
*
1716
* <pre>
1717
* file.setExecutable(arg, true) </pre>
1718
*
1719
* @param executable
1720
* If <code>true</code>, sets the access permission to allow execute
1721
* operations; if <code>false</code> to disallow execute operations
1722
*
1723
* @return <code>true</code> if and only if the operation succeeded. The
1724
* operation will fail if the user does not have permission to
1725
* change the access permissions of this abstract pathname. If
1726
* <code>executable</code> is <code>false</code> and the underlying
1727
* file system does not implement an execute permission, then the
1728
* operation will fail.
1729
*
1730
* @throws SecurityException
1731
* If a security manager exists and its <code>{@link
1732
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
1733
* method denies write access to the file
1734
*
1735
* @since 1.6
1736
*/
1737
public boolean setExecutable(boolean executable) {
1738
return setExecutable(executable, true);
1739
}
1740
1741
/**
1742
* Tests whether the application can execute the file denoted by this
1743
* abstract pathname. On some platforms it may be possible to start the
1744
* Java virtual machine with special privileges that allow it to execute
1745
* files that are not marked executable. Consequently this method may return
1746
* {@code true} even though the file does not have execute permissions.
1747
*
1748
* @return <code>true</code> if and only if the abstract pathname exists
1749
* <em>and</em> the application is allowed to execute the file
1750
*
1751
* @throws SecurityException
1752
* If a security manager exists and its <code>{@link
1753
* java.lang.SecurityManager#checkExec(java.lang.String)}</code>
1754
* method denies execute access to the file
1755
*
1756
* @since 1.6
1757
*/
1758
public boolean canExecute() {
1759
SecurityManager security = System.getSecurityManager();
1760
if (security != null) {
1761
security.checkExec(path);
1762
}
1763
if (isInvalid()) {
1764
return false;
1765
}
1766
return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE);
1767
}
1768
1769
1770
/* -- Filesystem interface -- */
1771
1772
/**
1773
* List the available filesystem roots.
1774
*
1775
* <p> A particular Java platform may support zero or more
1776
* hierarchically-organized file systems. Each file system has a
1777
* {@code root} directory from which all other files in that file system
1778
* can be reached. Windows platforms, for example, have a root directory
1779
* for each active drive; UNIX platforms have a single root directory,
1780
* namely {@code "/"}. The set of available filesystem roots is affected
1781
* by various system-level operations such as the insertion or ejection of
1782
* removable media and the disconnecting or unmounting of physical or
1783
* virtual disk drives.
1784
*
1785
* <p> This method returns an array of {@code File} objects that denote the
1786
* root directories of the available filesystem roots. It is guaranteed
1787
* that the canonical pathname of any file physically present on the local
1788
* machine will begin with one of the roots returned by this method.
1789
*
1790
* <p> The canonical pathname of a file that resides on some other machine
1791
* and is accessed via a remote-filesystem protocol such as SMB or NFS may
1792
* or may not begin with one of the roots returned by this method. If the
1793
* pathname of a remote file is syntactically indistinguishable from the
1794
* pathname of a local file then it will begin with one of the roots
1795
* returned by this method. Thus, for example, {@code File} objects
1796
* denoting the root directories of the mapped network drives of a Windows
1797
* platform will be returned by this method, while {@code File} objects
1798
* containing UNC pathnames will not be returned by this method.
1799
*
1800
* <p> Unlike most methods in this class, this method does not throw
1801
* security exceptions. If a security manager exists and its {@link
1802
* SecurityManager#checkRead(String)} method denies read access to a
1803
* particular root directory, then that directory will not appear in the
1804
* result.
1805
*
1806
* @return An array of {@code File} objects denoting the available
1807
* filesystem roots, or {@code null} if the set of roots could not
1808
* be determined. The array will be empty if there are no
1809
* filesystem roots.
1810
*
1811
* @since 1.2
1812
* @see java.nio.file.FileStore
1813
*/
1814
public static File[] listRoots() {
1815
return fs.listRoots();
1816
}
1817
1818
1819
/* -- Disk usage -- */
1820
1821
/**
1822
* Returns the size of the partition <a href="#partName">named</a> by this
1823
* abstract pathname.
1824
*
1825
* @return The size, in bytes, of the partition or <tt>0L</tt> if this
1826
* abstract pathname does not name a partition
1827
*
1828
* @throws SecurityException
1829
* If a security manager has been installed and it denies
1830
* {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>
1831
* or its {@link SecurityManager#checkRead(String)} method denies
1832
* read access to the file named by this abstract pathname
1833
*
1834
* @since 1.6
1835
*/
1836
public long getTotalSpace() {
1837
SecurityManager sm = System.getSecurityManager();
1838
if (sm != null) {
1839
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1840
sm.checkRead(path);
1841
}
1842
if (isInvalid()) {
1843
return 0L;
1844
}
1845
return fs.getSpace(this, FileSystem.SPACE_TOTAL);
1846
}
1847
1848
/**
1849
* Returns the number of unallocated bytes in the partition <a
1850
* href="#partName">named</a> by this abstract path name.
1851
*
1852
* <p> The returned number of unallocated bytes is a hint, but not
1853
* a guarantee, that it is possible to use most or any of these
1854
* bytes. The number of unallocated bytes is most likely to be
1855
* accurate immediately after this call. It is likely to be made
1856
* inaccurate by any external I/O operations including those made
1857
* on the system outside of this virtual machine. This method
1858
* makes no guarantee that write operations to this file system
1859
* will succeed.
1860
*
1861
* @return The number of unallocated bytes on the partition or <tt>0L</tt>
1862
* if the abstract pathname does not name a partition. This
1863
* value will be less than or equal to the total file system size
1864
* returned by {@link #getTotalSpace}.
1865
*
1866
* @throws SecurityException
1867
* If a security manager has been installed and it denies
1868
* {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>
1869
* or its {@link SecurityManager#checkRead(String)} method denies
1870
* read access to the file named by this abstract pathname
1871
*
1872
* @since 1.6
1873
*/
1874
public long getFreeSpace() {
1875
SecurityManager sm = System.getSecurityManager();
1876
if (sm != null) {
1877
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1878
sm.checkRead(path);
1879
}
1880
if (isInvalid()) {
1881
return 0L;
1882
}
1883
return fs.getSpace(this, FileSystem.SPACE_FREE);
1884
}
1885
1886
/**
1887
* Returns the number of bytes available to this virtual machine on the
1888
* partition <a href="#partName">named</a> by this abstract pathname. When
1889
* possible, this method checks for write permissions and other operating
1890
* system restrictions and will therefore usually provide a more accurate
1891
* estimate of how much new data can actually be written than {@link
1892
* #getFreeSpace}.
1893
*
1894
* <p> The returned number of available bytes is a hint, but not a
1895
* guarantee, that it is possible to use most or any of these bytes. The
1896
* number of unallocated bytes is most likely to be accurate immediately
1897
* after this call. It is likely to be made inaccurate by any external
1898
* I/O operations including those made on the system outside of this
1899
* virtual machine. This method makes no guarantee that write operations
1900
* to this file system will succeed.
1901
*
1902
* @return The number of available bytes on the partition or <tt>0L</tt>
1903
* if the abstract pathname does not name a partition. On
1904
* systems where this information is not available, this method
1905
* will be equivalent to a call to {@link #getFreeSpace}.
1906
*
1907
* @throws SecurityException
1908
* If a security manager has been installed and it denies
1909
* {@link RuntimePermission}<tt>("getFileSystemAttributes")</tt>
1910
* or its {@link SecurityManager#checkRead(String)} method denies
1911
* read access to the file named by this abstract pathname
1912
*
1913
* @since 1.6
1914
*/
1915
public long getUsableSpace() {
1916
SecurityManager sm = System.getSecurityManager();
1917
if (sm != null) {
1918
sm.checkPermission(new RuntimePermission("getFileSystemAttributes"));
1919
sm.checkRead(path);
1920
}
1921
if (isInvalid()) {
1922
return 0L;
1923
}
1924
return fs.getSpace(this, FileSystem.SPACE_USABLE);
1925
}
1926
1927
/* -- Temporary files -- */
1928
1929
private static class TempDirectory {
1930
private TempDirectory() { }
1931
1932
// temporary directory location
1933
private static final File tmpdir = new File(AccessController
1934
.doPrivileged(new GetPropertyAction("java.io.tmpdir")));
1935
static File location() {
1936
return tmpdir;
1937
}
1938
1939
// file name generation
1940
private static final SecureRandom random = new SecureRandom();
1941
static File generateFile(String prefix, String suffix, File dir)
1942
throws IOException
1943
{
1944
long n = random.nextLong();
1945
if (n == Long.MIN_VALUE) {
1946
n = 0; // corner case
1947
} else {
1948
n = Math.abs(n);
1949
}
1950
1951
// Use only the file name from the supplied prefix
1952
prefix = (new File(prefix)).getName();
1953
1954
String name = prefix + Long.toString(n) + suffix;
1955
File f = new File(dir, name);
1956
if (!name.equals(f.getName()) || f.isInvalid()) {
1957
if (System.getSecurityManager() != null)
1958
throw new IOException("Unable to create temporary file");
1959
else
1960
throw new IOException("Unable to create temporary file, " + f);
1961
}
1962
return f;
1963
}
1964
}
1965
1966
/**
1967
* <p> Creates a new empty file in the specified directory, using the
1968
* given prefix and suffix strings to generate its name. If this method
1969
* returns successfully then it is guaranteed that:
1970
*
1971
* <ol>
1972
* <li> The file denoted by the returned abstract pathname did not exist
1973
* before this method was invoked, and
1974
* <li> Neither this method nor any of its variants will return the same
1975
* abstract pathname again in the current invocation of the virtual
1976
* machine.
1977
* </ol>
1978
*
1979
* This method provides only part of a temporary-file facility. To arrange
1980
* for a file created by this method to be deleted automatically, use the
1981
* <code>{@link #deleteOnExit}</code> method.
1982
*
1983
* <p> The <code>prefix</code> argument must be at least three characters
1984
* long. It is recommended that the prefix be a short, meaningful string
1985
* such as <code>"hjb"</code> or <code>"mail"</code>. The
1986
* <code>suffix</code> argument may be <code>null</code>, in which case the
1987
* suffix <code>".tmp"</code> will be used.
1988
*
1989
* <p> To create the new file, the prefix and the suffix may first be
1990
* adjusted to fit the limitations of the underlying platform. If the
1991
* prefix is too long then it will be truncated, but its first three
1992
* characters will always be preserved. If the suffix is too long then it
1993
* too will be truncated, but if it begins with a period character
1994
* (<code>'.'</code>) then the period and the first three characters
1995
* following it will always be preserved. Once these adjustments have been
1996
* made the name of the new file will be generated by concatenating the
1997
* prefix, five or more internally-generated characters, and the suffix.
1998
*
1999
* <p> If the <code>directory</code> argument is <code>null</code> then the
2000
* system-dependent default temporary-file directory will be used. The
2001
* default temporary-file directory is specified by the system property
2002
* <code>java.io.tmpdir</code>. On UNIX systems the default value of this
2003
* property is typically <code>"/tmp"</code> or <code>"/var/tmp"</code>; on
2004
* Microsoft Windows systems it is typically <code>"C:\\WINNT\\TEMP"</code>. A different
2005
* value may be given to this system property when the Java virtual machine
2006
* is invoked, but programmatic changes to this property are not guaranteed
2007
* to have any effect upon the temporary directory used by this method.
2008
*
2009
* @param prefix The prefix string to be used in generating the file's
2010
* name; must be at least three characters long
2011
*
2012
* @param suffix The suffix string to be used in generating the file's
2013
* name; may be <code>null</code>, in which case the
2014
* suffix <code>".tmp"</code> will be used
2015
*
2016
* @param directory The directory in which the file is to be created, or
2017
* <code>null</code> if the default temporary-file
2018
* directory is to be used
2019
*
2020
* @return An abstract pathname denoting a newly-created empty file
2021
*
2022
* @throws IllegalArgumentException
2023
* If the <code>prefix</code> argument contains fewer than three
2024
* characters
2025
*
2026
* @throws IOException If a file could not be created
2027
*
2028
* @throws SecurityException
2029
* If a security manager exists and its <code>{@link
2030
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
2031
* method does not allow a file to be created
2032
*
2033
* @since 1.2
2034
*/
2035
public static File createTempFile(String prefix, String suffix,
2036
File directory)
2037
throws IOException
2038
{
2039
if (prefix.length() < 3)
2040
throw new IllegalArgumentException("Prefix string too short");
2041
if (suffix == null)
2042
suffix = ".tmp";
2043
2044
File tmpdir = (directory != null) ? directory
2045
: TempDirectory.location();
2046
SecurityManager sm = System.getSecurityManager();
2047
File f;
2048
do {
2049
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
2050
2051
if (sm != null) {
2052
try {
2053
sm.checkWrite(f.getPath());
2054
} catch (SecurityException se) {
2055
// don't reveal temporary directory location
2056
if (directory == null)
2057
throw new SecurityException("Unable to create temporary file");
2058
throw se;
2059
}
2060
}
2061
} while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);
2062
2063
if (!fs.createFileExclusively(f.getPath()))
2064
throw new IOException("Unable to create temporary file");
2065
2066
return f;
2067
}
2068
2069
/**
2070
* Creates an empty file in the default temporary-file directory, using
2071
* the given prefix and suffix to generate its name. Invoking this method
2072
* is equivalent to invoking <code>{@link #createTempFile(java.lang.String,
2073
* java.lang.String, java.io.File)
2074
* createTempFile(prefix,&nbsp;suffix,&nbsp;null)}</code>.
2075
*
2076
* <p> The {@link
2077
* java.nio.file.Files#createTempFile(String,String,java.nio.file.attribute.FileAttribute[])
2078
* Files.createTempFile} method provides an alternative method to create an
2079
* empty file in the temporary-file directory. Files created by that method
2080
* may have more restrictive access permissions to files created by this
2081
* method and so may be more suited to security-sensitive applications.
2082
*
2083
* @param prefix The prefix string to be used in generating the file's
2084
* name; must be at least three characters long
2085
*
2086
* @param suffix The suffix string to be used in generating the file's
2087
* name; may be <code>null</code>, in which case the
2088
* suffix <code>".tmp"</code> will be used
2089
*
2090
* @return An abstract pathname denoting a newly-created empty file
2091
*
2092
* @throws IllegalArgumentException
2093
* If the <code>prefix</code> argument contains fewer than three
2094
* characters
2095
*
2096
* @throws IOException If a file could not be created
2097
*
2098
* @throws SecurityException
2099
* If a security manager exists and its <code>{@link
2100
* java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
2101
* method does not allow a file to be created
2102
*
2103
* @since 1.2
2104
* @see java.nio.file.Files#createTempDirectory(String,FileAttribute[])
2105
*/
2106
public static File createTempFile(String prefix, String suffix)
2107
throws IOException
2108
{
2109
return createTempFile(prefix, suffix, null);
2110
}
2111
2112
/* -- Basic infrastructure -- */
2113
2114
/**
2115
* Compares two abstract pathnames lexicographically. The ordering
2116
* defined by this method depends upon the underlying system. On UNIX
2117
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
2118
* systems it is not.
2119
*
2120
* @param pathname The abstract pathname to be compared to this abstract
2121
* pathname
2122
*
2123
* @return Zero if the argument is equal to this abstract pathname, a
2124
* value less than zero if this abstract pathname is
2125
* lexicographically less than the argument, or a value greater
2126
* than zero if this abstract pathname is lexicographically
2127
* greater than the argument
2128
*
2129
* @since 1.2
2130
*/
2131
public int compareTo(File pathname) {
2132
return fs.compare(this, pathname);
2133
}
2134
2135
/**
2136
* Tests this abstract pathname for equality with the given object.
2137
* Returns <code>true</code> if and only if the argument is not
2138
* <code>null</code> and is an abstract pathname that denotes the same file
2139
* or directory as this abstract pathname. Whether or not two abstract
2140
* pathnames are equal depends upon the underlying system. On UNIX
2141
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
2142
* systems it is not.
2143
*
2144
* @param obj The object to be compared with this abstract pathname
2145
*
2146
* @return <code>true</code> if and only if the objects are the same;
2147
* <code>false</code> otherwise
2148
*/
2149
public boolean equals(Object obj) {
2150
if ((obj != null) && (obj instanceof File)) {
2151
return compareTo((File)obj) == 0;
2152
}
2153
return false;
2154
}
2155
2156
/**
2157
* Computes a hash code for this abstract pathname. Because equality of
2158
* abstract pathnames is inherently system-dependent, so is the computation
2159
* of their hash codes. On UNIX systems, the hash code of an abstract
2160
* pathname is equal to the exclusive <em>or</em> of the hash code
2161
* of its pathname string and the decimal value
2162
* <code>1234321</code>. On Microsoft Windows systems, the hash
2163
* code is equal to the exclusive <em>or</em> of the hash code of
2164
* its pathname string converted to lower case and the decimal
2165
* value <code>1234321</code>. Locale is not taken into account on
2166
* lowercasing the pathname string.
2167
*
2168
* @return A hash code for this abstract pathname
2169
*/
2170
public int hashCode() {
2171
return fs.hashCode(this);
2172
}
2173
2174
/**
2175
* Returns the pathname string of this abstract pathname. This is just the
2176
* string returned by the <code>{@link #getPath}</code> method.
2177
*
2178
* @return The string form of this abstract pathname
2179
*/
2180
public String toString() {
2181
return getPath();
2182
}
2183
2184
/**
2185
* WriteObject is called to save this filename.
2186
* The separator character is saved also so it can be replaced
2187
* in case the path is reconstituted on a different host type.
2188
* <p>
2189
* @serialData Default fields followed by separator character.
2190
*/
2191
private synchronized void writeObject(java.io.ObjectOutputStream s)
2192
throws IOException
2193
{
2194
s.defaultWriteObject();
2195
s.writeChar(separatorChar); // Add the separator character
2196
}
2197
2198
/**
2199
* readObject is called to restore this filename.
2200
* The original separator character is read. If it is different
2201
* than the separator character on this system, then the old separator
2202
* is replaced by the local separator.
2203
*/
2204
private synchronized void readObject(java.io.ObjectInputStream s)
2205
throws IOException, ClassNotFoundException
2206
{
2207
ObjectInputStream.GetField fields = s.readFields();
2208
String pathField = (String)fields.get("path", null);
2209
char sep = s.readChar(); // read the previous separator char
2210
if (sep != separatorChar)
2211
pathField = pathField.replace(sep, separatorChar);
2212
String path = fs.normalize(pathField);
2213
UNSAFE.putObject(this, PATH_OFFSET, path);
2214
UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path));
2215
}
2216
2217
private static final long PATH_OFFSET;
2218
private static final long PREFIX_LENGTH_OFFSET;
2219
private static final sun.misc.Unsafe UNSAFE;
2220
static {
2221
try {
2222
sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
2223
PATH_OFFSET = unsafe.objectFieldOffset(
2224
File.class.getDeclaredField("path"));
2225
PREFIX_LENGTH_OFFSET = unsafe.objectFieldOffset(
2226
File.class.getDeclaredField("prefixLength"));
2227
UNSAFE = unsafe;
2228
} catch (ReflectiveOperationException e) {
2229
throw new Error(e);
2230
}
2231
}
2232
2233
2234
/** use serialVersionUID from JDK 1.0.2 for interoperability */
2235
private static final long serialVersionUID = 301077366599181567L;
2236
2237
// -- Integration with java.nio.file --
2238
2239
private volatile transient Path filePath;
2240
2241
/**
2242
* Returns a {@link Path java.nio.file.Path} object constructed from the
2243
* this abstract path. The resulting {@code Path} is associated with the
2244
* {@link java.nio.file.FileSystems#getDefault default-filesystem}.
2245
*
2246
* <p> The first invocation of this method works as if invoking it were
2247
* equivalent to evaluating the expression:
2248
* <blockquote><pre>
2249
* {@link java.nio.file.FileSystems#getDefault FileSystems.getDefault}().{@link
2250
* java.nio.file.FileSystem#getPath getPath}(this.{@link #getPath getPath}());
2251
* </pre></blockquote>
2252
* Subsequent invocations of this method return the same {@code Path}.
2253
*
2254
* <p> If this abstract pathname is the empty abstract pathname then this
2255
* method returns a {@code Path} that may be used to access the current
2256
* user directory.
2257
*
2258
* @return a {@code Path} constructed from this abstract path
2259
*
2260
* @throws java.nio.file.InvalidPathException
2261
* if a {@code Path} object cannot be constructed from the abstract
2262
* path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath})
2263
*
2264
* @since 1.7
2265
* @see Path#toFile
2266
*/
2267
public Path toPath() {
2268
Path result = filePath;
2269
if (result == null) {
2270
synchronized (this) {
2271
result = filePath;
2272
if (result == null) {
2273
result = FileSystems.getDefault().getPath(path);
2274
filePath = result;
2275
}
2276
}
2277
}
2278
return result;
2279
}
2280
}
2281
2282