Delete all files in the specified folder through the File class method in Java

Delete all files in the specified folder through the File class method in Java

Insert picture description here

  • Explanation of delete
  • Insert picture description here
    So here comes the question!!!
    (The question in ②, how to delete all the files in the folder, presumably many students are as embarrassed as me,)
    Don’t worry (look down)
    Insert picture description here
    Insert picture description here
    the method to be used
    Insert picture description here

(Recursive thinking) If there are folders in the folder, continue to look down (maybe not official, personal understanding)

Next code display
Method 1:

package com.study;

import java.io.File;
import java.io.IOException;
/**
 1. 应用场景
 2.     delete删除只能删除空文件夹 和文件
 3.     删除指定文件夹
 */
public class Test1 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File f = new File("D://B");
        deleteFile(f);//删除完后并没有删除根目录
        f.delete();//删除根目录
        if (!f.exists()){
    
    
            //控制台打印
            System.out.println("删除成功");
        }
    }
    private static void deleteFile(File file) throws IOException {
    
    
        /**
         *  File[] listFiles() 
         *    返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。 
         */
        File[] files = file.listFiles();
        if (files!=null){
    
    //如果包含文件进行删除操作
            for (int i = 0; i <files.length ; i++) {
    
    
                if (files[i].isFile()){
    
    
                    //删除子文件
                    files[i].delete();
                }else if (files[i].isDirectory()){
    
    
                    //通过递归的方法找到子目录的文件
                    deleteFile(files[i]);
                }
                files[i].delete();//删除子目录
            }
        }
    }
}

Method 2: Same as above, just replace the above if code block

if (files!=null){//如果包含文件进行删除操作
            for (File f:files) {
                //判断遍历出的文件是不是文件
                if (f.isFile()){
                    //如果是则直接删除
                    f.delete();
                }else if (f.isDirectory()){//通过递归的方法找到文件夹里的文件
                    deleteFile(f);
                }
                f.delete();//删除子目录
            }
         }

Ideas

Delete the entire contents of the folder through the File class:

  1. The directory can be deleted only after all files in the directory are deleted
  2. Enter subdirectories recursively
  3. Finally delete the root directory

Guess you like

Origin blog.csdn.net/weixin_54282421/article/details/112250763