【发布时间】:2017-01-09 00:23:15
【问题描述】:
如何删除包含 Java 内容的整个目录? 我已经尝试了一些代码,但它不起作用。
public static void removeRecursive(Path path) throws IOException
{
Files.walkFileTree(path, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
// try to delete the file anyway, even if its attributes
// could not be read, since delete-only access is
// theoretically possible
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
{
if (exc == null)
{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
else
{
// directory iteration failed; propagate exception
throw exc;
}
}
});
}
它抛出一个错误:
D:\MainDir\chantier : 讲课错误。 字符串索引超出范围:-1
这是我的道路 D:\MainDir\ch\Lot\dossier\mail.zip
我想用他的内容删除目录 ch\Lot\dossier\mail.zip 但我的功能只删除 \dossier\mail.zip 并抛出提到的错误
Ps : 我作为输入文件 D:\MainDir\ch
提前致谢
【问题讨论】:
-
请添加完整的堆栈跟踪
-
我认为
FileVisitor在这里不是一个好的选择。查看this question 获取一些简单的解决方案。 -
@jens 这是它显示的唯一错误
-
@ImaneJabal 一定还有更多。打印出堆栈跟踪
标签: java