jdk8刪除非空文件夾,拷貝自StackOverflow

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;

/**
 * 多個文件相關的複雜操作,組合到一起
 * 
 * @author shenyanfang
 * @date 2018年7月12日
 */
public class FileExtUtil {
    public static Boolean ensureExistEmptyDir(String absPath) {
        File localDir = new File(absPath);
        try {
            // 確保存在空的project 文件夾
            if (!localDir.exists()) {
                localDir.mkdirs();
            } else {
                // 清空文件夾
                // Files.walk - return all files/directories below rootPath including
                // .sorted - sort the list in reverse order, so the directory itself comes after the including
                // subdirectories and files
                // .map - map the Path to File
                // .peek - is there only to show which entry is processed
                // .forEach - calls the .delete() method on every File object
                System.out.println("刪除目錄:");
                Files.walk(Paths.get(absPath)).sorted(Comparator.reverseOrder()).map(Path::toFile)
                        .peek(System.out::println).forEach(File::delete);
                System.out.println("清空目錄:" + absPath + "成功");
            }
            return Boolean.TRUE;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.FALSE;
    }
}

java 8 delete non empty directory

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章