wang-hao-jie
2022-08-25 57dcc73636bb7d8dce89c808eb8cc988a7512264
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.ruoyi.common.core.lang;
 
/**
 * 字节转换工具
 * @author ThinkGem
 * @version 2015-6-20
 */
public class ByteUtils {
 
    private static final int UNIT = 1024;
 
    /**
     * @param byteSize 字节
     * @return
     */
    public static String formatByteSize(long byteSize) {
        
        if (byteSize <= -1){
            return String.valueOf(byteSize);
        }
 
        double size = 1.0 * byteSize;
 
        String type = "B";
        if((int)Math.floor(size / UNIT) <= 0) { //不足1KB
            type = "B";
            return format(size, type);
        }
 
        size = size / UNIT;
        if((int)Math.floor(size / UNIT) <= 0) { //不足1MB
            type = "KB";
            return format(size, type);
        }
 
        size = size / UNIT;
        if((int)Math.floor(size / UNIT) <= 0) { //不足1GB
            type = "MB";
            return format(size, type);
        }
 
        size = size / UNIT;
        if((int)Math.floor(size / UNIT) <= 0) { //不足1TB
            type = "GB";
            return format(size, type);
        }
 
        size = size / UNIT;
        if((int)Math.floor(size / UNIT) <= 0) { //不足1PB
            type = "TB";
            return format(size, type);
        }
 
        size = size / UNIT;
        if((int)Math.floor(size / UNIT) <= 0) {
            type = "PB";
            return format(size, type);
        }
        return ">PB";
    }
 
    private static String format(double size, String type) {
        int precision = 0;
 
        if(size * 1000 % 10 > 0) {
            precision = 3;
        } else if(size * 100 % 10 > 0) {
            precision = 2;
        } else if(size * 10 % 10 > 0) {
            precision = 1;
        } else {
            precision = 0;
        }
 
        String formatStr = "%." + precision + "f";
 
        if("KB".equals(type)) {
            return String.format(formatStr, (size)) + "KB";
        } else if("MB".equals(type)) {
            return String.format(formatStr, (size)) + "MB";
        } else if("GB".equals(type)) {
            return String.format(formatStr, (size)) + "GB";
        } else if("TB".equals(type)) {
            return String.format(formatStr, (size)) + "TB";
        } else if("PB".equals(type)) {
            return String.format(formatStr, (size)) + "PB";
        }
        return  String.format(formatStr, (size)) + "B";
    }
 
}