Java中byte大小格式化

洼地云 tuoyidashi.png

JAVA.jpg

方法一

    public static String readableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

方法二

    public static String humanReadableByteCount(long bytes, boolean si) {
        int unit = si ? 1000 : 1024;
        if (bytes < unit) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }

方法三

使用org.apache.commons.io.FileUtils.byteCountToDisplaySize(long size)

FileUtils.byteCountToDisplaySize(long size)

参考:

  1. Format file size as MB, GB etc
  2. How to convert byte size into human readable format in java?
  3. JavaDoc for byteCountToDisplaySize
赞(0)
未经允许禁止转载:优米格 » Java中byte大小格式化

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册