FileUtils.java 1.83 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
package cn.timer.api.utils;


/**
 * @author wuqingjun
 * @email 284718418@qq.com
 * @date 2022/1/11
 */
public class FileUtils {
    /**
     * 获取文件的大小(返回到达的最高单位)
     * 比如:1024Byte就不再用Byte
     * 直接返回1KB
284718418@qq.com committed
14
     * 返回值精确到小数点后2位
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
     * @param size 文件大小
     * @return 文件的大小 若文件不存在或者不是文件就返回 “”
     */

    public static String getSize(long size) {
        double s = (double) size;
        String unit;
        if (size != -1L) {
            int l;
            if (size < 1024L) {
                l = 0;
            } else if (size < 1024L * 1024L) {
                l = 1;
                s = (double) size / 1024L;
            } else {
                for (l = 2; size >= 1024L * 1024L; l++) {
                    size = size / 1024L;
                    if ((size / 1024L) < 1024L) {
                        s = (double) size / 1024L;
                        break;
                    }
                }
            }
            switch (l) {
                case 0:
                    unit = "Byte";
                    break;
                case 1:
                    unit = "KB";
                    break;
                case 2:
                    unit = "MB";
                    break;
                case 3:
                    unit = "GB";
                    break;
                case 4:
                    unit = "TB";
                    break;
                default:
                    unit = "ER";
            }
284718418@qq.com committed
57
            String format = String.format("%.2f", s);
58 59 60 61 62 63 64 65 66 67 68
            return format + unit;
        }
        return "";
    }

    public static void main(String[] args) {
        System.out.println(getSize(42721));
        System.out.println(getSize(18560));
        System.out.println(getSize(37516712));
    }
}