Как рекурсивно удалить папку без следующих символических ссылок? - PullRequest
2 голосов
/ 29 декабря 2011

Я использовал Apache Commons ' FileUtils.deleteDirectory () , чтобы рекурсивно удалить папку, и заметил, что она следует по символическим ссылкам.

Есть ли альтернатива, которая не будет следовать символическим ссылкам, а будет только удалять реальные файлы и папки? Или я могу настроить FileUtils для этого?

Ответы [ 2 ]

2 голосов
/ 21 апреля 2015

Я сократил ответ 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 голос
/ 29 декабря 2011

Кажется, что все проблемы связаны с ошибкой аппарата в FileUtils.isSymlink() (я только что сообщил об этом). Я скопировал вставленный код для deleteDirectory() и использовал API Java 7 для проверки символических ссылок, и он работает:

public static void deleteDirectory(File directory) throws IOException {
    // See /6954976/kak-rekursivno-udalit-papku-bez-sleduyschih-simvolicheskih-ssylok
    // 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);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...