Android 获取目录剩余空间

sancaiodm Android源码摘录 2023-04-16 871 0
     /**
     * Get the remaining storage size in the given file path.
     *
     * @param storagePath
     *            String
     * @return remaining size in MB
     */
	private int mAvailableStorageSize = -1;
	mAvailableStorageSize = Utils.getAvailableStorageSize(mSDCardPathStr);
    public static int getAvailableStorageSize(String storagePath) {
        StatFs stat;
        int retryNum = 1;
        while (retryNum <= 3) {
            try {
                stat = new StatFs(storagePath);
                long blockSize = stat.getBlockSizeLong();
                long availableBlocks = stat.getAvailableBlocksLong();
                int availableSize = (int) (availableBlocks * blockSize / (1024 * 1024));
                Utils.logd(TAG, "-->getAvailableStorageSize(), path=" + storagePath + ", size="
                        + availableSize + "MB");
                return availableSize;
            } catch (IllegalArgumentException e) {
                Utils.logw(TAG, "Fail to get storage info from [" + storagePath
                        + "] by StatFs, try again(index=" + retryNum + ").");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            retryNum++;
        }
        Utils.loge(TAG, "-->getAvailableStorageSize(), fail to get it by StatFs,"
                + " unknown exception happen.");
        return 0;
    }


评论