Folder operations:



1: 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 above string name

3: Call 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();
  }
}


Second: 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 the file is a directory, the directory has a lower 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] + " 是一个目录");
        } else {
          System.out.println(s[i] + " 是一个文件");
        }
      }
    } else {
      System.out.println(dirname + " 不是一个目录");
    }
  }
}


3: Delete directories and files

1: Create a file stream: File folder=new File(path)

2: Use an array to record other files in the directory: File[] files=folder.listFiles();

3: Traverse the array, the method is the same as finding Directory

4: Delete directory: deleteFolder(folder);

5: Delete file: f.delete()

import java.io.File;
 
public class DeleteFileDemo {
  public static void main(String args[]) {
      // Modify it 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();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324794970&siteId=291194637