The File object calls the method public boolean mkdir() to create a directory. If the creation is successful, it returns true, otherwise it returns false. If the directory already exists, it returns false.
If the File object is a directory, then the object calls the following method to list the files and subdirectories in the directory.
Returns all files in the directory in string form.
Returns all files in the directory in the form of File objects.
Sometimes it is necessary to list files of specified types in a directory, such as files with .java, .txt and other extensions. We can use the following two methods of the File class to list files of a specified type.
This method returns all files of the specified type in the directory in string form.
This method returns all files of the specified type in the directory in the form of File objects.
The parameter FilenameFilter of the above two methods is an interface, which has one method:
publicbooleanaccept(Filedir,Stringname);
When the File object dirFile calls the list method, it needs to pass an object that implements the FilenameFilter interface to the method. When the list method is executed, the parameter obj continuously calls back the interface method accept(File dir, String name). The parameter dir in this method is the one that calls the list. The current directory dirFile, the parameter name is instantiated as a file name in the dirFile directory. When the interface method returns true, the list method stores the file named name into the returned array.
For example, list the names of all .java files in the current directory (the directory where the application is located):
importjava.io.*;publicclassMain{publicstaticvoidmain(Stringargs[]){FiledirFile=newFile(.);FileAcceptfileAccept=newFileAccept();fileAccept.setExtendName(java);StringfileName[]=dirFile.list(fileAccept);for(Stringname: fileName){System.out.println(name);}}}