Java IO File, javaiofile
A file class is a class library tool used to obtain files and folders. A File is not just used to represent files as a class name, but can also be used to represent folders. Therefore, you can use File to obtain all the files in a directory, or even files in a folder.
A simple way to get all files and folders in the current file directory
Public static void dir () {File dir = new File (". ");//". "String [] files = dir. list (); // obtain all the file arrays in the path for (String s: files) System. out. println (s );}
You can also use this method to recursively retrieve all file trees under the specified directory and all descendant directories.
Public static void allFiles (String path, int layer) {File file = new File (path); // create the directory String [] files = file according to the path. list (); File temp; for (String s: files) {String p = path + "/" + s; // construct a new path for (int I = 0; I <layer; I ++) System. out. print ("\ t"); System. out. println ("|-" + s); temp = new File (p); if (temp. isDirectory () // if the File is a directory (that is, a folder), the File allFiles (p, layer + 1) in this directory is recursively displayed );}}
The layer parameter is used to indicate the directory depth, which can be easily indented Based on the depth of the file tree.
If you want to delete or select a file directory, you can provide the list () method with an object that implements the FilenameFilter interface, overwrite the accept () method, and use a regular expression to match the file name.
Public static void fileFilter () {File file = new File (". "); String files; for (String s: file. list (new FilenameFilter () {// implement a FilenameFilter instance through an anonymous internal class, and implement the accept method @ Override public boolean accept (File dir, String name) {return Pattern. compile (". *\\. java "). matcher (name ). matches (); // use a regular expression to match the file name ". java "End file}) {System. out. println (s );}}
The File class has the following common methods:
Public String getName (); // get the file name public String getParent (); // obtain the parent path public String getAbsolutePath (); // obtain the absolute path public boolean canRead () in the computer; // whether the file is readable public boolean canWrite (); // whether the file can be written public boolean canExecute (); // whether the file can execute public boolean exists (); // whether the file has public boolean isDirectory (); // whether it is a folder (directory) public boolean isFile (); // whether the object is public boolean isHidden (); // whether to hide public long length (); // obtain the object length public boolean createNewFile (); // create a new file public boolean delete (); // delete the file