Java Delete File Recursively deleteRecursively(File file)

Here you can find the source of deleteRecursively(File file)

Description

delete Recursively

License

Apache License

Declaration

public static void deleteRecursively(File file) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import com.google.common.base.Preconditions;

import java.io.File;
import java.io.IOException;

public class Main {
    public static void deleteRecursively(File file) throws IOException {
        if (file == null) {
            return;
        }/*from  w ww  .j av a2s .co  m*/

        if (file.isDirectory() && !isSymlink(file)) {
            IOException savedIOException = null;
            for (File child : listFilesSafely(file)) {
                try {
                    deleteRecursively(child);
                } catch (IOException e) {
                    // In case of multiple exceptions, only last one will be thrown
                    savedIOException = e;
                }
            }
            if (savedIOException != null) {
                throw savedIOException;
            }
        }

        boolean deleted = file.delete();
        // Delete can also fail if the file simply did not exist.
        if (!deleted && file.exists()) {
            throw new IOException("Failed to delete: " + file.getAbsolutePath());
        }
    }

    private static boolean isSymlink(File file) throws IOException {
        Preconditions.checkNotNull(file);
        File fileInCanonicalDir = null;
        if (file.getParent() == null) {
            fileInCanonicalDir = file;
        } else {
            fileInCanonicalDir = new File(file.getParentFile().getCanonicalFile(), file.getName());
        }
        return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());

    }

    private static File[] listFilesSafely(File file) throws IOException {
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files == null) {
                throw new IOException("Failed to list files for dir: " + file);
            }
            return files;
        } else {
            return new File[0];
        }
    }
}

Related

  1. deleteRecursively(File file)
  2. deleteRecursively(File file)
  3. deleteRecursively(File file)
  4. deleteRecursively(File file)
  5. deleteRecursively(File file)
  6. deleteRecursively(File file)
  7. deleteRecursively(File file)
  8. deleteRecursively(File file)
  9. deleteRecursively(File file)