Folder operations:
One: create a directory
1: Define the created directory String name="C://path//path"
2: Instantiate the file class: File file=new File(name); //Accept the string name above
3: Call the method to create a directory: file.mkdirs();
import java.io.File; public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = new File(dirname); // now create the directory d.mkdirs(); } }
Two: find the directory
1: Define the initial directory: String name = "c://"
2: Instantiate the file class: File file =new File(name);
3: Determine whether the file is a directory if (file.isDirectory)
4: If file is a directory, the directory has the next level, and the name of the directory is recorded with an array: String s[]=file.list();
5: Then recreate the file stream: File f1=new File(name+"\"+s[i]) //s[i] is the name of the file recorded in the fourth step
import java.io.File; public class DirList { public static void main(String args[]) { String dirname = "/tmp"; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println( "目录 " + dirname); String s[] = f1.list(); for (int i=0; i < s.length; i++) { File f = new File(dirname + "/" + s[i]); if (f.isDirectory()) { System.out.println(s[i] + "is a directory"); } else { System.out.println(s[i] + "is a file"); } } } else { System.out.println(dirname + "is not a directory"); } } }
Three: delete directories and files
1: Create a file stream: File folder=new File(path)
2: Use an array to record other files under the directory: File[] files=folder.listFiles();
3: Traverse the array, the method is the same as finding the directory
4: Delete a directory: deleteFolder(folder);
5: Delete file: f.delete()
import java.io.File; public class DeleteFileDemo { public static void main(String args[]) { // Modify here to your own test directory File folder = new File("/tmp/java/"); deleteFolder(folder); } // delete files and directories public static void deleteFolder(File folder) { File[] files = folder.listFiles(); if(files!=null) { for(File f: files) { if(f.isDirectory()) { deleteFolder(f); } else { f.delete(); } } } folder.delete(); } }