-
Notifications
You must be signed in to change notification settings - Fork 669
/
Copy pathFile.java
2616 lines (2341 loc) · 114 KB
/
File.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import jdk.internal.misc.Unsafe;
import sun.security.action.GetPropertyAction;
/**
* An abstract representation of file and directory pathnames.
*
* <p> User interfaces and operating systems use system-dependent <em>pathname
* strings</em> to name files and directories. This class presents an
* abstract, system-independent view of hierarchical pathnames. An
* <em>abstract pathname</em> has two components:
*
* <ol>
* <li> An optional system-dependent <em>prefix</em> string,
* such as a disk-drive specifier, <code>"/"</code> for the UNIX root
* directory, or <code>"\\\\"</code> for a Microsoft Windows UNC pathname, and
* <li> A sequence of zero or more string <em>names</em>.
* </ol>
*
* The first name in an abstract pathname may be a directory name or, in the
* case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name
* in an abstract pathname denotes a directory; the last name may denote
* either a directory or a file. The <em>empty</em> abstract pathname has no
* prefix and an empty name sequence.
*
* <p> The conversion of a pathname string to or from an abstract pathname is
* inherently system-dependent. When an abstract pathname is converted into a
* pathname string, each name is separated from the next by a single copy of
* the default <em>separator character</em>. The default name-separator
* character is defined by the system property <code>file.separator</code>, and
* is made available in the public static fields {@link
* #separator} and {@link #separatorChar} of this class.
* When a pathname string is converted into an abstract pathname, the names
* within it may be separated by the default name-separator character or by any
* other name-separator character that is supported by the underlying system.
*
* <p> A pathname, whether abstract or in string form, may be either
* <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in
* that no other information is required in order to locate the file that it
* denotes. A relative pathname, in contrast, must be interpreted in terms of
* information taken from some other pathname. By default the classes in the
* <code>java.io</code> package always resolve relative pathnames against the
* current user directory. This directory is named by the system property
* <code>user.dir</code>, and is typically the directory in which the Java
* virtual machine was invoked.
*
* <p> The <em>parent</em> of an abstract pathname may be obtained by invoking
* the {@link #getParent} method of this class and consists of the pathname's
* prefix and each name in the pathname's name sequence except for the last.
* Each directory's absolute pathname is an ancestor of any {@code File}
* object with an absolute abstract pathname which begins with the directory's
* absolute pathname. For example, the directory denoted by the abstract
* pathname {@code "/usr"} is an ancestor of the directory denoted by the
* pathname {@code "/usr/local/bin"}.
*
* <p> The prefix concept is used to handle root directories on UNIX platforms,
* and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms,
* as follows:
*
* <ul>
*
* <li> For UNIX platforms, the prefix of an absolute pathname is always
* <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname
* denoting the root directory has the prefix <code>"/"</code> and an empty
* name sequence.
*
* <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive
* specifier consists of the drive letter followed by <code>":"</code> and
* possibly followed by <code>"\\"</code> if the pathname is absolute. The
* prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share
* name are the first two names in the name sequence. A relative pathname that
* does not specify a drive has no prefix.
*
* </ul>
*
* <p> Instances of this class may or may not denote an actual file-system
* object such as a file or a directory. If it does denote such an object
* then that object resides in a <i>partition</i>. A partition is an
* operating system-specific portion of storage for a file system. A single
* storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may
* contain multiple partitions. The object, if any, will reside on the
* partition <a id="partName">named</a> by some ancestor of the absolute
* form of this pathname.
*
* <p> A file system may implement restrictions to certain operations on the
* actual file-system object, such as reading, writing, and executing. These
* restrictions are collectively known as <i>access permissions</i>. The file
* system may have multiple sets of access permissions on a single object.
* For example, one set may apply to the object's <i>owner</i>, and another
* may apply to all other users. The access permissions on an object may
* cause some methods in this class to fail.
*
* <p> Instances of the <code>File</code> class are immutable; that is, once
* created, the abstract pathname represented by a <code>File</code> object
* will never change.
*
* <h3>Interoperability with {@code java.nio.file} package</h3>
*
* <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>
* package defines interfaces and classes for the Java virtual machine to access
* files, file attributes, and file systems. This API may be used to overcome
* many of the limitations of the {@code java.io.File} class.
* The {@link #toPath toPath} method may be used to obtain a {@link
* Path} that uses the abstract path represented by a {@code File} object to
* locate a file. The resulting {@code Path} may be used with the {@link
* java.nio.file.Files} class to provide more efficient and extensive access to
* additional file operations, file attributes, and I/O exceptions to help
* diagnose errors when an operation on a file fails.
*
* @author unascribed
* @since 1.0
*/
// 对操作系统中【文件】和【目录】的抽象
public class File implements Serializable, Comparable<File> {
/**
* The FileSystem object representing the platform's local file system.
*/
// 文件系统(此处以Windows为例)
private static final FileSystem fs = DefaultFileSystem.getFileSystem();
/**
* The system-dependent default name-separator character. This field is
* initialized to contain the first character of the value of the system
* property <code>file.separator</code>. On UNIX systems the value of this
* field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>.
*
* @see java.lang.System#getProperty(java.lang.String)
*/
// 路径内部的分隔符:Windows系统上是'\',类Unix系统上是'/'
public static final char separatorChar = fs.getSeparator();
/**
* The system-dependent default name-separator character, represented as a
* string for convenience. This string contains a single character, namely
* {@link #separatorChar}.
*/
// 路径内部的分隔符:Windows系统上是"\",类Unix系统上是"/"
public static final String separator = "" + separatorChar;
/**
* The system-dependent path-separator character. This field is
* initialized to contain the first character of the value of the system
* property <code>path.separator</code>. This character is used to
* separate filenames in a sequence of files given as a <em>path list</em>.
* On UNIX systems, this character is <code>':'</code>; on Microsoft Windows systems it
* is <code>';'</code>.
*
* @see java.lang.System#getProperty(java.lang.String)
*/
// 路径之间的分隔符:Windows系统上是';',类Unix系统上是':'
public static final char pathSeparatorChar = fs.getPathSeparator();
/**
* The system-dependent path-separator character, represented as a string
* for convenience. This string contains a single character, namely
* {@link #pathSeparatorChar}.
*/
// 路径之间的分隔符:Windows系统上是";",类Unix系统上是":"
public static final String pathSeparator = "" + pathSeparatorChar;
/**
* The flag indicating whether the file path is invalid.
*/
// File路径有效性标记
private transient PathStatus status = null;
/**
* This abstract pathname's normalized pathname string.
* A normalized pathname string uses the default name-separator character
* and does not contain any duplicate or redundant separators.
*
* @serial
*/
// File的本地化路径(忽略最后的'\',除非是根目录)
private final String path;
/**
* The length of this abstract pathname's prefix, or zero if it has no prefix.
*/
/*
* 本地化路径的前缀长度
*
* 0 - 相对路径,如相对路径"a\b"
* 1 - 磁盘相对路径,如"\a\b"
* 2 - UNC路径,如"\\a\b",或目录相对路径,如"c:a\b"
* 3 - 绝对路径,如"c:\a\b"
*/
private final transient int prefixLength;
// 当前File的本地化路径的Path表示
private transient volatile Path filePath;
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new <code>File</code> instance by converting the given
* pathname string into an abstract pathname. If the given string is
* the empty string, then the result is the empty abstract pathname.
*
* @param pathname A pathname string
*
* @throws NullPointerException If the <code>pathname</code> argument is <code>null</code>
*/
// 用指定的路径名初始化File
public File(String pathname) {
if(pathname == null) {
throw new NullPointerException();
}
// 获取本地化路径(忽略最后的'\',除非是根目录)
this.path = fs.normalize(pathname);
// 获取本地化路径的前缀长度
this.prefixLength = fs.prefixLength(this.path);
}
/*
* Note: The two-argument File constructors do not interpret an empty parent abstract pathname as the current user directory.
* An empty parent instead causes the child to be resolved against the system-dependent directory defined by the FileSystem.getDefaultParent method.
* On Unix this default is "/", while on Microsoft Windows it is "\\".
* This is required for compatibility with the original behavior of this class.
*/
/**
* Creates a new <code>File</code> instance from a parent pathname string and a child pathname string.
*
* <p> If <code>parent</code> is <code>null</code> then the new
* <code>File</code> instance is created as if by invoking the
* single-argument <code>File</code> constructor on the given
* <code>child</code> pathname string.
*
* <p> Otherwise the <code>parent</code> pathname string is taken to denote
* a directory, and the <code>child</code> pathname string is taken to
* denote either a directory or a file. If the <code>child</code> pathname
* string is absolute then it is converted into a relative pathname in a
* system-dependent way. If <code>parent</code> is the empty string then
* the new <code>File</code> instance is created by converting
* <code>child</code> into an abstract pathname and resolving the result
* against a system-dependent default directory. Otherwise each pathname
* string is converted into an abstract pathname and the child abstract
* pathname is resolved against the parent.
*
* @param parent The parent pathname string
* @param child The child pathname string
*
* @throws NullPointerException If <code>child</code> is <code>null</code>
*/
// 用父路径名称与子路径名称构造一个File
public File(String parent, String child) {
if(child == null) {
throw new NullPointerException();
}
if(parent != null) {
String pp;
String cp;
if(parent.equals("")) {
pp = fs.getDefaultParent(); // 返回默认的父级路径::Windows系统上是'\',类Unix系统上是'/'
cp = fs.normalize(child); // 返回本地化路径
} else {
pp = fs.normalize(parent); // 返回本地化路径
cp = fs.normalize(child); // 返回本地化路径
}
// 返回拼接后的本地化路径
this.path = fs.resolve(pp, cp);
} else {
this.path = fs.normalize(child);
}
// 获取本地化路径的前缀长度
this.prefixLength = fs.prefixLength(this.path);
}
/**
* Creates a new <code>File</code> instance from a parent abstract
* pathname and a child pathname string.
*
* <p> If <code>parent</code> is <code>null</code> then the new
* <code>File</code> instance is created as if by invoking the
* single-argument <code>File</code> constructor on the given
* <code>child</code> pathname string.
*
* <p> Otherwise the <code>parent</code> abstract pathname is taken to
* denote a directory, and the <code>child</code> pathname string is taken
* to denote either a directory or a file. If the <code>child</code>
* pathname string is absolute then it is converted into a relative
* pathname in a system-dependent way. If <code>parent</code> is the empty
* abstract pathname then the new <code>File</code> instance is created by
* converting <code>child</code> into an abstract pathname and resolving
* the result against a system-dependent default directory. Otherwise each
* pathname string is converted into an abstract pathname and the child
* abstract pathname is resolved against the parent.
*
* @param parent The parent abstract pathname
* @param child The child pathname string
*
* @throws NullPointerException If <code>child</code> is <code>null</code>
*/
// 使用父级File与子路径构造一个File
public File(File parent, String child) {
if(child == null) {
throw new NullPointerException();
}
if(parent != null) {
String pp;
String cp;
if(parent.path.equals("")) {
pp = fs.getDefaultParent(); // 返回默认的父级路径::Windows系统上是'\',类Unix系统上是'/'
cp = fs.normalize(child); // 返回本地化路径
} else {
pp = parent.path;
cp = fs.normalize(child); // 返回本地化路径
}
// 返回拼接后的本地化路径
this.path = fs.resolve(pp, cp);
} else {
this.path = fs.normalize(child);
}
// 获取本地化路径的前缀长度
this.prefixLength = fs.prefixLength(this.path);
}
/**
* Creates a new {@code File} instance by converting the given
* {@code file:} URI into an abstract pathname.
*
* <p> The exact form of a {@code file:} URI is system-dependent, hence
* the transformation performed by this constructor is also
* system-dependent.
*
* <p> For a given abstract pathname <i>f</i> it is guaranteed that
*
* <blockquote><code>
* new File(</code><i> f</i><code>.{@link #toURI()
* toURI}()).equals(</code><i> f</i><code>.{@link #getAbsoluteFile() getAbsoluteFile}())
* </code></blockquote>
*
* so long as the original abstract pathname, the URI, and the new abstract
* pathname are all created in (possibly different invocations of) the same
* Java virtual machine. This relationship typically does not hold,
* however, when a {@code file:} URI that is created in a virtual machine
* on one operating system is converted into an abstract pathname in a
* virtual machine on a different operating system.
*
* @param uri An absolute, hierarchical URI with a scheme equal to
* {@code "file"}, a non-empty path component, and undefined
* authority, query, and fragment components
*
* @throws NullPointerException If {@code uri} is {@code null}
* @throws IllegalArgumentException If the preconditions on the parameter do not hold
* @see #toURI()
* @see java.net.URI
* @since 1.4
*/
// 使用指定的uri资源构造文件对象
public File(URI uri) {
// Check our many preconditions
if(!uri.isAbsolute()) {
throw new IllegalArgumentException("URI is not absolute");
}
if(uri.isOpaque()) {
throw new IllegalArgumentException("URI is not hierarchical");
}
String scheme = uri.getScheme();
if((scheme == null) || !scheme.equalsIgnoreCase("file")) {
throw new IllegalArgumentException("URI scheme is not \"file\"");
}
if(uri.getRawAuthority() != null) {
throw new IllegalArgumentException("URI has an authority component");
}
if(uri.getRawFragment() != null) {
throw new IllegalArgumentException("URI has a fragment component");
}
if(uri.getRawQuery() != null) {
throw new IllegalArgumentException("URI has a query component");
}
// 从uri中解析出路径
String path = uri.getPath();
if(path.equals("")) {
throw new IllegalArgumentException("URI path component is empty");
}
// 对uri中解析出的path进行后处理,将其转换为普通路径
path = fs.fromURIPath(path);
// 如果路径内分隔符不是'/',将路径的'/'替换为本地化的路径内分隔符
if(File.separatorChar != '/') {
path = path.replace('/', File.separatorChar);
}
// 返回本地化路径
this.path = fs.normalize(path);
// 获取本地化路径的前缀长度
this.prefixLength = fs.prefixLength(this.path);
}
/**
* Internal constructor for already-normalized pathname strings.
*/
private File(String pathname, int prefixLength) {
this.path = pathname;
this.prefixLength = prefixLength;
}
/**
* Internal constructor for already-normalized pathname strings.
* The parameter order is used to disambiguate this method from the public(File, String) constructor.
*/
private File(String child, File parent) {
assert parent.path != null;
assert (!parent.path.equals(""));
// 返回拼接后的本地化路径
this.path = fs.resolve(parent.path, child);
// 获取本地化路径的前缀长度
this.prefixLength = parent.prefixLength;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 创建 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates the directory named by this abstract pathname.
*
* @return <code>true</code> if and only if the directory was
* created; <code>false</code> otherwise
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method does not permit the named directory to be created
*/
/*
* 创建【目录】,当该【目录】的父级【目录】存在,且该【目录】本身不存在时,才会创建成功
* 注:不允许创建未知的多级目录
*/
public boolean mkdir() {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkWrite(path);
}
if(isInvalid()) {
return false;
}
// 创建【目录】,返回值指示是否创建成功
return fs.createDirectory(this);
}
/**
* Creates the directory named by this abstract pathname, including any
* necessary but nonexistent parent directories. Note that if this
* operation fails it may have succeeded in creating some of the necessary
* parent directories.
*
* @return <code>true</code> if and only if the directory was created,
* along with all necessary parent directories; <code>false</code>
* otherwise
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkRead(java.lang.String)}
* method does not permit verification of the existence of the
* named directory and all necessary parent directories; or if
* the {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method does not permit the named directory and all necessary
* parent directories to be created
*/
/*
* 创建【目录】,当该【目录】本身不存在时,才会创建成功
* 注:允许创建未知的多级目录
*/
public boolean mkdirs() {
if(exists()) {
return false;
}
// 先尝试单级目录的创建
if(mkdir()) {
return true;
}
File canonFile = null;
try {
// 获取基于规范路径形式的File
canonFile = getCanonicalFile();
} catch(IOException e) {
return false;
}
// 获取基于父级本地化路径的File
File parent = canonFile.getParentFile();
return parent != null && (parent.mkdirs() || parent.exists()) // 先创建父级File
&& canonFile.mkdir(); // 再创建字级File
}
/**
* Atomically creates a new, empty file named by this abstract pathname if
* and only if a file with this name does not yet exist. The check for the
* existence of the file and the creation of the file if it does not exist
* are a single operation that is atomic with respect to all other
* filesystem activities that might affect the file.
* <P>
* Note: this method should <i>not</i> be used for file-locking, as
* the resulting protocol cannot be made to work reliably. The
* {@link java.nio.channels.FileLock FileLock}
* facility should be used instead.
*
* @return <code>true</code> if the named file does not exist and was
* successfully created; <code>false</code> if the named file
* already exists
*
* @throws IOException If an I/O error occurred
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
* @since 1.2
*/
// 创建【文件】,仅当文件还未创建,且文件所在目录存在时,才会创建成功
public boolean createNewFile() throws IOException {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkWrite(path);
}
if(isInvalid()) {
throw new IOException("Invalid file path");
}
return fs.createFileExclusively(path);
}
/**
* Creates an empty file in the default temporary-file directory, using
* the given prefix and suffix to generate its name. Invoking this method
* is equivalent to invoking {@link #createTempFile(java.lang.String,
* java.lang.String, java.io.File)
* createTempFile(prefix, suffix, null)}.
*
* <p> The {@link
* java.nio.file.Files#createTempFile(String, String, java.nio.file.attribute.FileAttribute[])
* Files.createTempFile} method provides an alternative method to create an
* empty file in the temporary-file directory. Files created by that method
* may have more restrictive access permissions to files created by this
* method and so may be more suited to security-sensitive applications.
*
* @param prefix The prefix string to be used in generating the file's
* name; must be at least three characters long
* @param suffix The suffix string to be used in generating the file's
* name; may be <code>null</code>, in which case the
* suffix <code>".tmp"</code> will be used
*
* @return An abstract pathname denoting a newly-created empty file
*
* @throws IllegalArgumentException If the <code>prefix</code> argument contains fewer than three
* characters
* @throws IOException If a file could not be created
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method does not allow a file to be created
* @see java.nio.file.Files#createTempDirectory(String, FileAttribute[])
* @since 1.2
*/
// 在系统默认用户数据临时目录[java.io.tmpdir]下创建带有前缀prefix和后缀suffix的【临时文件】
public static File createTempFile(String prefix, String suffix) throws IOException {
return createTempFile(prefix, suffix, null);
}
/**
* <p> Creates a new empty file in the specified directory, using the
* given prefix and suffix strings to generate its name. If this method
* returns successfully then it is guaranteed that:
*
* <ol>
* <li> The file denoted by the returned abstract pathname did not exist
* before this method was invoked, and
* <li> Neither this method nor any of its variants will return the same
* abstract pathname again in the current invocation of the virtual
* machine.
* </ol>
*
* This method provides only part of a temporary-file facility. To arrange
* for a file created by this method to be deleted automatically, use the
* {@link #deleteOnExit} method.
*
* <p> The <code>prefix</code> argument must be at least three characters
* long. It is recommended that the prefix be a short, meaningful string
* such as <code>"hjb"</code> or <code>"mail"</code>. The
* <code>suffix</code> argument may be <code>null</code>, in which case the
* suffix <code>".tmp"</code> will be used.
*
* <p> To create the new file, the prefix and the suffix may first be
* adjusted to fit the limitations of the underlying platform. If the
* prefix is too long then it will be truncated, but its first three
* characters will always be preserved. If the suffix is too long then it
* too will be truncated, but if it begins with a period character
* (<code>'.'</code>) then the period and the first three characters
* following it will always be preserved. Once these adjustments have been
* made the name of the new file will be generated by concatenating the
* prefix, five or more internally-generated characters, and the suffix.
*
* <p> If the <code>directory</code> argument is <code>null</code> then the
* system-dependent default temporary-file directory will be used. The
* default temporary-file directory is specified by the system property
* <code>java.io.tmpdir</code>. On UNIX systems the default value of this
* property is typically <code>"/tmp"</code> or <code>"/var/tmp"</code>; on
* Microsoft Windows systems it is typically <code>"C:\\WINNT\\TEMP"</code>. A different
* value may be given to this system property when the Java virtual machine
* is invoked, but programmatic changes to this property are not guaranteed
* to have any effect upon the temporary directory used by this method.
*
* @param prefix The prefix string to be used in generating the file's
* name; must be at least three characters long
* @param suffix The suffix string to be used in generating the file's
* name; may be <code>null</code>, in which case the
* suffix <code>".tmp"</code> will be used
* @param directory The directory in which the file is to be created, or
* <code>null</code> if the default temporary-file
* directory is to be used
*
* @return An abstract pathname denoting a newly-created empty file
*
* @throws IllegalArgumentException If the <code>prefix</code> argument contains fewer than three
* characters
* @throws IOException If a file could not be created
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method does not allow a file to be created
* @since 1.2
*/
/*
* 在目录directory下创建带有前缀prefix和后缀suffix的【临时文件】
*
* 如果directory为null,即不指定【临时文件】的目录,则使用用户数据临时目录
* 例如在windows下,默认的用户数据临时目录为:C:\Users\kang\AppData\Local\Temp\
* 可以通过指定系统属性:java.io.tmpdir来改变默认的用户数据临时目录位置
*/
public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
// 前缀长度至少为3
if(prefix.length()<3) {
throw new IllegalArgumentException("Prefix string \"" + prefix + "\" too short: length must be at least 3");
}
// 后缀默认是.tmp,对长度没要求
if(suffix == null) {
suffix = ".tmp";
}
// 获取【临时文件】所在目录
File tmpdir = (directory != null) ? directory // 指定目录
: TempDirectory.location(); // 默认目录
File file;
do {
// 在目录tmpdir下创建带有前缀prefix和后缀suffix的【临时文件】
file = TempDirectory.generateFile(prefix, suffix, tmpdir);
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
try {
sm.checkWrite(file.getPath());
} catch(SecurityException se) {
// don't reveal temporary directory location
if(directory == null) {
throw new SecurityException("Unable to create temporary file");
}
throw se;
}
}
} while((fs.getBooleanAttributes(file) & FileSystem.BA_EXISTS) != 0);
if(!fs.createFileExclusively(file.getPath())) {
throw new IOException("Unable to create temporary file");
}
return file;
}
/*▲ 创建 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 删除 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Deletes the file or directory denoted by this abstract pathname. If
* this pathname denotes a directory, then the directory must be empty in
* order to be deleted.
*
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
* java.nio.file.Files#delete(Path) delete} method to throw an {@link IOException}
* when a file cannot be deleted. This is useful for error reporting and to
* diagnose why a file cannot be deleted.
*
* @return <code>true</code> if and only if the file or directory is
* successfully deleted; <code>false</code> otherwise
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkDelete} method denies
* delete access to the file
*/
// 删除File,仅当【文件】存在,或【目录】存在且为空时,删除成功
public boolean delete() {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkDelete(path);
}
if(isInvalid()) {
return false;
}
return fs.delete(this);
}
/**
* Requests that the file or directory denoted by this abstract
* pathname be deleted when the virtual machine terminates.
* Files (or directories) are deleted in the reverse order that
* they are registered. Invoking this method to delete a file or
* directory that is already registered for deletion has no effect.
* Deletion will be attempted only for normal termination of the
* virtual machine, as defined by the Java Language Specification.
*
* <p> Once deletion has been requested, it is not possible to cancel the
* request. This method should therefore be used with care.
*
* <P>
* Note: this method should <i>not</i> be used for file-locking, as
* the resulting protocol cannot be made to work reliably. The
* {@link java.nio.channels.FileLock FileLock}
* facility should be used instead.
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkDelete} method denies
* delete access to the file
* @see #delete
* @since 1.2
*/
/*
* 在虚拟机退出时删除File,仅当【文件】存在,或【目录】存在且为空时,删除成功。
* 与delete()方法的区别是:delete()会立即删除文件,而deleteOnExit()不会立即删除,但保证在虚拟机退出之前删除。
* 该方法用来删除临时文件很合适。
*/
public void deleteOnExit() {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkDelete(path);
}
if(isInvalid()) {
return;
}
// 注册一个钩子,在虚拟机关闭时删除此文件
DeleteOnExitHook.add(path);
}
/*▲ 删除 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 重命名 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Renames the file denoted by this abstract pathname.
*
* <p> Many aspects of the behavior of this method are inherently
* platform-dependent: The rename operation might not be able to move a
* file from one filesystem to another, it might not be atomic, and it
* might not succeed if a file with the destination abstract pathname
* already exists. The return value should always be checked to make sure
* that the rename operation was successful.
*
* <p> Note that the {@link java.nio.file.Files} class defines the {@link
* java.nio.file.Files#move move} method to move or rename a file in a
* platform independent manner.
*
* @param dest The new abstract pathname for the named file
*
* @return <code>true</code> if and only if the renaming succeeded;
* <code>false</code> otherwise
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to either the old or new pathnames
* @throws NullPointerException If parameter <code>dest</code> is <code>null</code>
*/
/*
* 重命名当前File为newFile
*
* 重命名实质上是改变了File实体的路径信息,所以,重命名操作兼具"移动"功能。
*/
public boolean renameTo(File newFile) {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkWrite(path);
security.checkWrite(newFile.path);
}
if(newFile == null) {
throw new NullPointerException();
}
if(this.isInvalid() || newFile.isInvalid()) {
return false;
}
return fs.rename(this, newFile);
}
/*▲ 重命名 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 杂项 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Tests whether the file or directory denoted by this abstract pathname
* exists.
*
* @return <code>true</code> if and only if the file or directory denoted
* by this abstract pathname exists; <code>false</code> otherwise
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkRead(java.lang.String)}
* method denies read access to the file or directory
*/
/*
* 判断当前File是否存在
*
* 实际应用前最好先转换为绝对(路径)File或规范(路径)File,然后再进行判断
*/
public boolean exists() {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkRead(path);
}
if(isInvalid()) {
return false;
}
return (fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0;
}
/**
* Tests whether the file denoted by this abstract pathname is a normal
* file. A file is <em>normal</em> if it is not a directory and, in
* addition, satisfies other system-dependent criteria. Any non-directory
* file created by a Java application is guaranteed to be a normal file.
*
* <p> Where it is required to distinguish an I/O exception from the case
* that the file is not a normal file, or where several attributes of the
* same file are required at the same time, then the {@link
* java.nio.file.Files#readAttributes(Path, Class, LinkOption[])
* Files.readAttributes} method may be used.
*
* @return <code>true</code> if and only if the file denoted by this
* abstract pathname exists <em>and</em> is a normal file;
* <code>false</code> otherwise
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkRead(java.lang.String)}
* method denies read access to the file
*/
/*
* 判断当前File是否为文件(只对存在的File有效)
*
* 实际应用前最好先转换为绝对(路径)File或规范(路径)File,然后再进行判断
*/
public boolean isFile() {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkRead(path);
}
if(isInvalid()) {
return false;
}
return (fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0;
}
/**
* Tests whether the file denoted by this abstract pathname is a
* directory.
*
* <p> Where it is required to distinguish an I/O exception from the case
* that the file is not a directory, or where several attributes of the
* same file are required at the same time, then the {@link
* java.nio.file.Files#readAttributes(Path, Class, LinkOption[])
* Files.readAttributes} method may be used.
*
* @return <code>true</code> if and only if the file denoted by this
* abstract pathname exists <em>and</em> is a directory;
* <code>false</code> otherwise
*
* @throws SecurityException If a security manager exists and its {@link
* java.lang.SecurityManager#checkRead(java.lang.String)}
* method denies read access to the file
*/
/*
* 判断当前File是否为目录(只对存在的File有效)
*
* 实际应用前最好先转换为绝对(路径)File或规范(路径)File,然后再进行判断
*/
public boolean isDirectory() {
SecurityManager security = System.getSecurityManager();
if(security != null) {
security.checkRead(path);
}
if(isInvalid()) {
return false;
}
return (fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY) != 0;
}
/**
* Returns the length of the file denoted by this abstract pathname.
* The return value is unspecified if this pathname denotes a directory.
*
* <p> Where it is required to distinguish an I/O exception from the case
* that {@code 0L} is returned, or where several attributes of the same file
* are required at the same time, then the {@link
* java.nio.file.Files#readAttributes(Path,Class,LinkOption[])
* Files.readAttributes} method may be used.
*
* @return The length, in bytes, of the file denoted by this abstract
* pathname, or <code>0L</code> if the file does not exist. Some
* operating systems may return <code>0L</code> for pathnames
* denoting system-dependent entities such as devices or pipes.
*