欢迎光临
感受代码之美

Java中byte大小格式化

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
转载请注明来源:四个空格 » Java中byte大小格式化

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址