1 about file. isFile () and file. isDirectory ()
If the Directory must be file, the file is not necessarily Directory.
Correct: file and Directory are two different things. They can only be one of file or Directory.
2 It doesn't mean that we execute a sentence File f = new File ("F: \ x.txt ");
An x.txt file is generated on an external hard disk.
Operation.
File f = new File ("F: \ x.txt ");
If (! F. exists ()){
F. createNewFile ();
}
F. createNewFile () indicates that an empty file is created.
3. For the directory, run file. mkdir (s) () first.
Save the file to it. For example:
File f = new File ("F: \ test \ x.txt ");
If (! F. exists ()){
F. createNewFile ();
}
Of course, an error is reported because the directory of x.txt does not exist !!
Therefore, it should be corrected:
File f = new File ("F: \ test \ x.txt ");
F. getParentFile (). mkdirs ();
If (! F. exists ()){
F. createNewFile ();
}
The same principle
File f = new File ("F: \ test \ x.txt ");
If (f. isFile ()){
System. out. println ("true ");
} Else {
System. out. println ("false ");
}
The result is false.
Therefore, a better practical experience should be as follows:
File file = new File ("E: \ zz \ xx \ 123.txt ");
// 1 first, determine whether the parent file exists. If not, create
// No matter how complicated the parent path is.
// For example, there is no zz or xx on an edisk.
// However, it will be created at this level
If (! File. getParentFile (). exists ()){
File. getParentFile (). mkdirs ();
}
// 2. Check whether the file exists. If the file does not exist, create
If (! File. exists ()){
Try {
File. createNewFile ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
4. Summarize the two File-related operations.
(1)
File f = new File ("");
F. createNewFile ();
Then perform operations on f.
Of course there is no error because f has been created
(2) file f = new File ("");
Then, stream operations are performed using the input and output streams.
For example:
File f = new File ("F: \ test.txt ");
FileOutputStream fos = new FileOutputStream (f );
String string = "hello ";
Byte [] B = string. getBytes ();
Fos. write (B, 0, B. length );
Question:
According to the idea in (1), f. createNewFile () is not executed. Why is no error reported ???
Because the output stream FileOutputStream has already done this job.
The following is an example of modification:
File f = new File ("F: \ 2221x.txt ");
If (f. isFile ()){
System. out. println ("true1 ");
} Else {
System. out. println ("false1 ");
}
FileOutputStream fos = new FileOutputStream (f );
If (f. isFile ()){
System. out. println ("true2 ");
} Else {
System. out. println ("false2 ");
}
String string = "hello ";
Byte [] B = string. getBytes ();
Fos. write (B, 0, B. length );
Output false1, true2
Verification is obtained.