1. 程式人生 > >監控資料夾下大小是否有變化

監控資料夾下大小是否有變化

問題場景

在寫定時器時遇到個問題,當定時器掃描某一固定資料夾下的內容進行處理時,可能這個資料夾還在被追加內容,這樣定時器處理的內容就不準確了,為了解決它,筆者準備了一個哨兵,在每次輪到定時器處理前讓哨兵進行一次檢測,通過檢測進行處理,否則這次任務跳過。

CODE

/**
     * 判斷指定目錄下檔案大小是否變化
     *
     * @param dir    監控的目錄絕對路徑
     * @param period 統計時間間隔,ms
     * @return -1 error;   0 no change;    1 change
     */
    public static int isChange(String dir, long period) throws InterruptedException {
        return isChange(new File(dir), period);
    }

    /**
     * 判斷指定目錄下檔案大小是否變化
     *
     * @param file   監控的檔案
     * @param period 統計時間間隔,ms
     * @return -1 error;   0 no change;    1 change
     */
    public static int isChange(File file, long period) throws InterruptedException {
        int res = -1;
        if (file.exists()) {
            long sizeA = getAllSize4File(file);
            if (sizeA > 0) {
                Thread.sleep(period);
                long sizeB = getAllSize4File(file);
                long result = sizeB - sizeA;
                if (result == 0) {
                    res = 0;
                } else {
                    res = 1;
                }
            }
        }
        return res;
    }

    /**
     * 獲取資料夾下的所有檔案的大小
     *
     * @param path 資料夾絕對路徑
     * @return
     */
    public static long getAllSize4File(String path) {
        return getAllSize4File(new File(path));
    }

    public static long getAllSize4File(File file) {
        long res = 0;
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        res += getAllSize4File(file1.getAbsolutePath());
                    } else {
                        res += file1.length();
                    }
                }
            } else {
                if (file.isFile()) {
                    res = file.length();
                }
            }
        }
        return res;
    }