Programs may often need to obtain information about files on the disk or create new files on the disk, etc. This requires learning to use the File class . It should be noted that the object of the File class is mainly used to obtain some information about the file itself, such as the directory where the file is located, the length of the file, or file read and write permissions, etc. It does not involve reading and writing operations on the file.
There are three constructors for creating a File object:
Among them, filename is the file name, directoryPath is the path of the file, and dir is a directory. When you create a file using File(String filename), the file is considered to be in the same directory as the current application.
Commonly used methods of the File class are as follows:
Get the name of the file.
Determine whether the file is readable.
Determine whether the file can be written.
Determine whether the file exists.
Get the length of the file (unit is bytes).
Get the absolute path of the file.
Get the parent directory of the file.
Determines whether the file is a regular file, not a directory.
Determine whether the file is a directory.
Determine whether the file is a hidden file.
Get the last modified time of the file (the time is the number of milliseconds from midnight 1970 to the last modified time of the file).
For example, create a new file named new.txt:
importjava.io.*;publicclassMain{publicstaticvoidmain(Stringargs[]){Filef=newFile(C:\ch10,Main.java);System.out.println(f.getName()+Is it readable:+f .canRead());System.out.println(f.getName()+absolute path:+f.getAbsolutePath());Filefile=newFile(new.txt);System.out.println(created in the current directory New file+file.getName());if(!file.exists()){try{file.createNewFile();System.out.println(created successfully);}catch(IOExceptionexp){}}}}
The running results are as follows:
Is C:ch10>java.MainMain.java readable: The absolute path of trueMain.java: C:ch10Main.java Create a new file new.txt in the current directory and create it successfully