Delete sub folder(FileUtils)

public class FileUtils {
    /** Delete all specified subFolder, e.g. delete all bin directory of c:/testApp. */
    public static void deleteSubFolder(String sPath, String subFoldName, boolean isRecurse) {
        File file = new File(sPath);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                if (f.getName().equals(subFoldName)) {
                    System.out.println("Delete folder: " + f.getAbsolutePath());
                    deleteFileOrFolder(f.getAbsolutePath());
                }
                else
                    deleteSubFolder(f.getAbsolutePath(), subFoldName, true);
            }
            //System.out.println(f.getName());
        }
    }

    /** Delete folder or file */
    public static boolean deleteFileOrFolder(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (!file.exists()) {
            return flag;
        } else {
            if (file.isFile())
                return deleteFile(sPath);
            else
                return deleteDirectory(sPath);

        }
    }

    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /** Delete directory and all childDirectory and files */
    public static boolean deleteDirectory(String sPath) {
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

你可能感兴趣的:(fileutil)