文件大小转换带上单位工具类(文件byte自动转KB\MB\GB)

   /**
     *
     * @param bytes 转换得字节
     * @param si 是否需要单位
     * @return
     */
    public static String byteFormat(long bytes, boolean si) {
        String[] units = new String[]{" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"};
        int unit = 1024;
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        double pre = 0;
        if (bytes > 1024) {
            pre = bytes / Math.pow(unit, exp);
        } else {
            pre = (double) bytes / (double) unit;
        }
        if (si) {
            return String.format(Locale.ENGLISH, "%.1f%s", pre, units[(int) exp]);
        }
        return String.format(Locale.ENGLISH, "%.1f", pre);
    }
posted @ 2020-06-12 17:01  proper128  阅读(827)  评论(0编辑  收藏  举报