Common APIs for Java-IO stream File, javaiofileapi
1. It is only used to indicate the information (name, size, etc.) of the file (directory) and cannot be used to access the file content.
Package cn. test; import java. io. file; import java. io. IOException; public class Demo16 {public static void main (String [] args) {File file = new File ("F: \ javaio"); // File (directory) if (! File. exists () {// create a directory file. mkdir (); // file. mkdirs ();} else {// file (directory) delete file. delete ();} // whether the directory is a directory. If the directory is not a directory or the directory does not exist, false System is returned. out. println (file. isDirectory (); // whether the file is System. out. println (file. isFile (); // File file2 = new File ("F: \ java \ note 1.txt"); File file2 = new File ("F: \ javaio ", "Diary 2.txt"); if (! File2.exists () {try {// create the file file2.createNewFile ();} catch (IOException e) {e. printStackTrace () ;}} else {file2.delete ();} System. out. println (file); System. out. println (file. getAbsolutePath (); // returns the absolute path System. out. println (file. getName (); // The directory name System. out. println (file2.getName (); // file name System. out. println (file. getParent (); // path of the parent directory: System. out. println (file. getParent (); // path of the parent directory }}
2. traverse directories
Package com. test. io; import java. io. file; import java. io. IOException;/*** common File operations ** @ author Administrator **/public class FileUtils {/*** list the specified directory (including its subdirectories) all files * @ param dir * @ throws IOException */public static void listDirectory (File dir) throws IOException {if (! Dir. exists () {throw new IllegalArgumentException ("directory" + dir + "does not exist");} if (! Dir. isDirectory () {throw new IllegalArgumentException (dir + "not a directory");}/* String [] filenames = dir. list (); // returns a String array that lists subdirectories and files in the current directory (excluding contents in subdirectories) for (string String: filenames) {System. out. println (dir + "\" + string);} * // If You Want to traverse the content in the subdirectory, You need to construct a File object for Recursive operation File [] files = dir. listFiles (); // return the abstract if (files! = Null & files. length> 0) {for (File file: files) {if (file. isDirectory () {// recursive listDirectory (file);} else {System. out. println (file );}}}}}