Android 代码转化文件大小为人类易懂的格式

    // print sizes in human readable format (e.g., 1K 23M 4G)
    public static String fileSizeToString(File file) {
        String size;
        DecimalFormat df = new DecimalFormat("#.##");

        if (file.exists()) {
            double bytes = file.length();
            /*
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            double gigabytes = (megabytes / 1024);
            double terabytes = (gigabytes / 1024);
            double petabytes = (terabytes / 1024);
            double exabytes = (petabytes / 1024);
            double zettabytes = (exabytes / 1024);
            double yottabytes = (zettabytes / 1024);
            */

            if (bytes < 1024) {
                size = df.format(bytes) + "B";
            } else if (bytes < 1024 * 1024) {
                size = df.format(bytes / 1024) + "K";
            } else if (bytes < 1024 * 1024 * 1024) {
                size = df.format(bytes / 1024 / 1024) + "M";
            } else if (bytes < 1024 * 1024 * 1024 * 1024) {
                size = df.format(bytes / 1024 / 1024 / 1024) + "G";
            } else if (bytes < 1024 * 1024 * 1024 * 1024 * 1024) {
                size = df.format(bytes / 1024 / 1024 / 1024 / 1024) + "T";
            } else if (bytes < 1024 * 1024 * 1024 * 1024 * 1024 * 1024) {
                size = df.format(bytes / 1024 / 1024 / 1024 / 1024 / 1024) + "P";
            } else {
                size = "huge";
            }
        } else {
            size = "error";
            Log.e(TAG, file.getName() + " can not be found");
        }

        return size;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容