/**
* 删除文件或级联删除目录及下的所有文件和目录
* @param fileStr 要删除的文件或目录
* @return true 删除成功 false 删除失败
* @throws IOException
*/
public static boolean deleteFileCascade(String fileStr) throws IOException {
File file = new File(fileStr);
if(!file.exists()) {
throw new FileNotFoundException("文件或目录不存在");
}
if(file.isFile()) {
return file.delete();
}
Files.walkFileTree(Paths.get(fileStr), new SimpleFileVisitor<Path>() {
/**
* 遍历到某个文件时执行
*/
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file); //删除文件
return super.visitFile(file, attrs);
}
/**
* 当退出某个目录时执行此方法
*/
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);//删除目录
return super.postVisitDirectory(dir, exc);
}
});
return true;
}
删除某个目录及下的所有子目录和文件
最新推荐文章于 2024-07-17 08:51:41 发布