英文:
Delete all files inside a directory - skipping system protected or opened ones
问题
我正在编写一个Java应用程序,在处理结束时会删除特定目录(而不是目录本身)中的所有文件。\n我尝试使用FileUtils.cleanDirectory()
,但是当目录中有受保护或正在被使用的文件时会失败。\n我只想跳过那些类型的文件并删除其他文件。\n请提供一个优雅的解决方案来处理这个问题。谢谢!
英文:
I am writing a Java application that removes all files inside a certain directory (not the directory itself) in the end of processing.
I tried to use FileUtils.cleanDirectory()
but it fails when there are protected or being-used files in the directory. I just want to skip those kind of files and remove others.
Please suggest a sleek solution to handle this. Thanks!
答案1
得分: 2
我认为解决方案是逐个删除文件,File.delete()
函数在删除文件失败时只会返回 false。
File directoryPath = new File("Directory");
File[] filesList = directoryPath.listFiles();
for(File file : filesList) {
try{
file.delete();
}catch(SecurityException e){
//被 SecurityManager 阻止
}
}
编辑:要递归删除,您可以使用 Files 类,
Path directory = Paths.get("Directory");
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try{
Files.delete(file);
}catch(Exception e){}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if(!dir.equals(directory)){
try{
Files.delete(dir);
}catch(Exception e){}
return FileVisitResult.CONTINUE;
}
}
});
英文:
I think the solution is to just delete the files individually, the File.delete()
function just returns false when it fails to delete the file.
File directoryPath = new File("Directory");
File[] filesList = directoryPath.listFiles();
for(File file : filesList) {
try{
file.delete();
}catch(SecurityException e){
//Prevented by SecurityManager
}
}
Edit: to recursively delete you can use the Files class,
Path directory = Paths.get("Directory");
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try{
Files.delete(file);
}catch(Exception e){}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if(!dir.equals(directory)){
try{
Files.delete(dir);
}catch(Exception e){}
return FileVisitResult.CONTINUE;
}
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论