美文网首页Android Utils
Android 代码转化文件大小为人类易懂的格式

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

作者: 几千里也 | 来源:发表于2015-04-23 11:00 被阅读27次
        // 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;
        }
    

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/oztpfttx.html