欢迎光临
我们一直在努力

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
赞(0)
未经允许不得转载:Ddmit » Java中byte大小格式化

评论 抢沙发

登录

找回密码

注册