我使用Apache Commons'FileUtils.deleteDirectory()以递归方式删除文件夹,我注意到它遵循符号链接。
是否有替代品不会遵循符号链接,但只删除真实文件和文件夹?或者,我可以调整FileUtils来执行此操作吗?
答案 0 :(得分:2)
我缩短了ripper234的答案。
/**
* Recursively deletes `item`, which may be a directory.
* Symbolic links will be deleted instead of their referents.
* Returns a boolean indicating whether `item` still exists.
* http://stackoverflow.com/questions/8666420
*/
public static boolean deleteRecursiveIfExists(File item) {
if (!item.exists()) return true;
if (!Files.isSymbolicLink(item.toPath()) && item.isDirectory()) {
File[] subitems = item.listFiles();
for (File subitem : subitems)
if (!deleteRecursiveIfExists(subitem)) return false;
}
return item.delete();
}
答案 1 :(得分:1)
整个问题似乎源于FileUtils.isSymlink()
中的明显错误(我刚刚报告过)。我复制粘贴deleteDirectory()
的代码,并使用Java 7的API代替检查符号链接,它可以工作:
public static void deleteDirectory(File directory) throws IOException {
// See http://stackoverflow.com/questions/8666420/how-to-recursively-delete-a-folder-without-following-symlinks
// Copied from http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/2.1/org/apache/commons/io/FileUtils.java#FileUtils.deleteDirectory%28java.io.File%29
if (!directory.exists()) {
return;
}
if (!Files.isSymbolicLink(directory.toPath())) {
cleanDirectory(directory);
}
if (!directory.delete()) {
String message = "Unable to delete directory " + directory + ".";
throw new IOException(message);
}
}
private static void cleanDirectory(File directory) throws IOException {
// Copied from http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/2.1/org/apache/commons/io/FileUtils.java#FileUtils.cleanDirectory%28java.io.File%29
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (File file : files) {
try {
forceDelete(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (exception != null) {
throw exception;
}
}
private 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);
}
}
}