1. 程式人生 > >檔案清理工具

檔案清理工具

/**
 * @author zhou.jn on 2018/11/28 10:39.
 */

public class FileCleanUtil {

    private static final String TAG = "FileCleanUtil";

    /**
     * @param context 清除本應用內部快取(/data/data/com.xxx.xxx/cache)
     */
    public static void cleanInternalCache(Context context) {
        deleteFileByDirectory(context.
getCacheDir()); } /** * @param context 清除/data/data/com.xxx.xxx/files下的內容 */ public static void cleanPackageFile(Context context) { deleteFileByDirectory(context.getFilesDir()); } /** * @param context 清除外部cache下的內容(/mnt/sdcard/android/data/com.xxx.xxx/cache) */ public
static void cleanExternalCache(Context context) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { deleteFileByDirectory(context.getExternalCacheDir()); } } /** * @param file 清除自定義路徑下的檔案,使用需小心,請不要誤刪。而且只支援目錄下的檔案刪除 */ public
static void cleanSpecifyDirectory(String file) { if (!TextUtils.isEmpty(file)) { deleteFileByDirectory(new File(file)); } } /** * @param path 根據檔案路徑,刪除單個檔案 */ public static void cleanSpecifyFile(String path) { File file = new File(path); if (file.exists()) { file.delete(); } } public static long getSdAvailableSize() { File storageDirectory = Environment.getExternalStorageDirectory(); StatFs statFs = new StatFs(storageDirectory.getPath()); long blockSize; long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFs.getBlockSizeLong(); availableBlocks = statFs.getAvailableBlocksLong(); } else { blockSize = statFs.getBlockSize(); availableBlocks = statFs.getAvailableBlocks(); } return blockSize * availableBlocks; } /** * @return 根據剩餘空間是否大於1G來預留空間提醒使用者是否可以進行下載 */ public boolean isAvailableByDownload() { long freeSize = getSdAvailableSize(); Slog.i(TAG, "isAvailableByDownload size: " + freeSize); //如果剩餘空間大於1G 則是可以下載的 1 int size = (int) (freeSize / (1024 * 1024 * 1024)); if (size >= 1) { return true; } else { return false; } } /** * @param fileSize 通過下載的檔案所需的空間大小來判斷使用者是否可以進行下載 * @return */ public boolean isAvailableByDownload(float fileSize) { long freeSize = getSdAvailableSize(); if (fileSize > fileSize) { return true; } else { return false; } } /** * @param directory 刪除該資料夾下的所有檔案, */ private static void deleteFileByDirectory(File directory) { if (directory != null && directory.exists() && directory.isDirectory()) { for (File item : directory.listFiles()) { item.delete(); } } } }