1. Information (name, size, etc.) that is used only to represent a file (directory) and cannot be used for access to file content.
Packagecn.test;ImportJava.io.File;Importjava.io.IOException; Public classDemo16 { Public Static voidMain (string[] args) {File file=NewFile ("F:\\javaio"); //whether the file (directory) exists if(!file.exists ()) { //Create a directoryFile.mkdir ();//file.mkdirs ();}Else { //file (directory) DeleteFile.delete (); } //whether it is a directory that returns true if it is not a directory or directory that does not exist returns falseSystem.out.println (File.isdirectory ()); //whether it is a fileSystem.out.println (File.isfile ()); //file File2 = new file ("F:\\java\\ diary 1.txt");File file2 =NewFile ("F:\\javaio", "Journal 2.txt"); if(!file2.exists ()) { Try { //Create a fileFile2.createnewfile (); } Catch(IOException e) {e.printstacktrace (); } } Else{file2.delete (); } System.out.println (file); System.out.println (File.getabsolutepath ());//return absolute path System.out.println (File.getname ());//directory name System.out.pri Ntln (File2.getname ());//File name System.out.println (File.getparent ());//Parent directory path SYSTEM.OUT.PRINTLN (file.getparen T ());//path to parent directory}}
2. Traversing the Directory
PackageCom.test.io;ImportJava.io.File;Importjava.io.IOException;/*** Common operation of File class *@authorAdministrator **/ Public classFileUtils {/*** List all files under the specified directory (including their subdirectories) *@paramdir *@throwsIOException*/ Public Static voidListDirectory (File dir)throwsioexception{if(!dir.exists ()) { Throw NewIllegalArgumentException ("directory" + dir + "does not exist"); } if(!dir.isdirectory ()) { Throw NewIllegalArgumentException (dir + "not directory"); } /*string[] filenames = dir.list ();//Returns a string array that lists subdirectories and files under the current directory (without subdirectories) for (string string:filenames) { System.out.println (dir + "\ \" +string); } */ //if you want to traverse the contents of a subdirectory, you need to construct the file object to do the recursive operationfile[] files = dir.listfiles ();//returns an abstraction of a direct subdirectory (file) if(Files! =NULL&& files.length > 0) { for(File file:files) {if(File.isdirectory ()) {//Recursivelistdirectory (file); } Else{System.out.println (file); } } } }}
Common APIs for the Java-io stream file class