1. 程式人生 > >刪除指定資料夾下的所有東西

刪除指定資料夾下的所有東西

package com.shi.zxing.QZxing.util;

import java.io.File;

/**
 * 刪除資料夾下所有的檔案
 * @author SHF
 * @version 建立時間:2018年10月29日  下午2:38:41
 */
public class DeleteDemo {
    public static void main(String[] args) {
        File f = new File(System.getProperty("user.dir")+"/data/");
        deleteFile(f);
    }

    public static void deleteFile(File file) {
        // 判斷傳遞進來的是檔案還是資料夾,如果是檔案,直接刪除,如果是資料夾,則判斷資料夾裡面有沒有東西
        if (file.isDirectory()) {
            // 如果是目錄,就刪除目錄下所有的檔案和資料夾
            File[] files = file.listFiles();
            // 遍歷目錄下的檔案和資料夾
            for (File f : files) {
                // 如果是檔案,就刪除
                if (f.isFile()) {
                    System.out.println("已經被刪除的檔案:" + f);
                    // 刪除檔案
                    f.delete();     
                } else if (file.isDirectory()) {
                    // 如果是資料夾,就遞迴呼叫資料夾的方法
                    deleteFile(f);
                }
            }
            // 刪除資料夾自己,如果它低下是空的,就會被刪除
            //System.out.println("已經被刪除的資料夾:" + file);
            //file.delete();
        }

        // 如果是檔案,就直接刪除自己
        System.out.println("已經被刪除的檔案:" + file);
        file.delete();
    }
}