java删除指定文件夹下所有文件和文件夹——FileUtils.forceDelete(File file)

主要是使用FileUtils.forceDelete(File file)工具类来删除目录下所有东西:

DeleteFolderDemo.java

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class DeleteFolderDemo {
    private static Path pathObj = Paths.get("src/test/resources/region/region_test.txt");
    public static boolean deleteFolder(File path) {
        try {
            //1.是文件:则删除
            //2.是目录:则“自动”递归删除指定目录下的所有文件和文件夹
            FileUtils.forceDelete(file);
            return true;
        } catch (IOException e) {
            return false;
        }
    public static void main(String[] args) {
    }
}

下面是FileUtils.forceDelete(File f)的源代码:

我们可以看到:
是目录:则调用了FileUtils.deleteDirectory(File directory)
是文件:则调用了file.delete()

    /**
     * Deletes a file. If file is a directory, delete it and all sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>You get exceptions when a file or directory cannot be deleted.
     *      (java.io.File methods returns a boolean)</li>
     * </ul>
     *
     * @param file  file or directory to delete, must not be {@code null}
     * @throws NullPointerException if the directory is {@code null}
     * @throws FileNotFoundException if the file was not found
     * @throws IOException in case deletion is unsuccessful
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        } else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent){
                    throw new FileNotFoundException("File does not exist: " + file);
                }
                String message =
                    "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }

 ps: 
若想调用FileUtils.deleteDirectory(File directory)  
注意:参数一定是目录,不能是指定文件!!否则报错:*** is not a directory

 

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值