1. 程式人生 > >jdk8刪除非空資料夾,拷貝自StackOverflow

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; } }