public class DeleteFileTest {

    public static void main(String[] args) {
        String deleteFilePath = "C:\\Users\\Hery\\Desktop\\文件夹测试";
        File deleteFile = new File(deleteFilePath);
        if (deleteFile.exists()) {
            if (deleteFile.isFile()) {
                System.out.println("删除" + deleteFile.getAbsolutePath());//文件路径
                if (deleteFile.delete()) {
                    System.out.println("删除目标文件成功");
                }
            } else if (deleteFile.isDirectory()) {
                List<Boolean> deleteStateList = new ArrayList<>();
                recursionRemove(deleteFile, deleteStateList);
                if (deleteStateList.stream().allMatch(eachDeleteState -> eachDeleteState == true)) {
                    System.out.println("删除目标文件夹成功");
                }
            }
        } else {
            System.out.println("目标文件(夹)不存在");
        }
    }

    /**
     * 递归删除文件夹下的子目录与文件
     *
     * @param targetFile      目标文件
     * @param deleteStateList 记录文件删除状态
     */
    private static void recursionRemove(File targetFile, List<Boolean> deleteStateList) {
        File[] filesArr = targetFile.listFiles();
        for (File f : filesArr) {
            if (f.isFile()) {
                System.out.println("删除" + f.getAbsolutePath());//文件路径
                deleteStateList.add(f.delete());
            } else if (f.isDirectory()) {
                recursionRemove(f, deleteStateList);
            }
        }
        System.out.println("删除" + targetFile.getAbsolutePath());//文件路径
        deleteStateList.add(targetFile.delete());
    }
}

 

posted on 2023-03-27 13:52  加贝聪明  阅读(326)  评论(0编辑  收藏  举报