文件清理工具

/**
 * @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();
            }
        }
    }
}

你可能感兴趣的:(Android,Utils)