Browse Source

增加文件大小单位转换

dsx 2 năm trước cách đây
mục cha
commit
033422c784

+ 1 - 0
4dkankan-common-utils/src/main/java/com/fdkankan/common/constant/ErrorCode.java

@@ -81,6 +81,7 @@ public enum ErrorCode {
     FAILURE_CODE_3033(3033, "60秒内不能重复获取验证码"),
 
     FAILURE_CODE_4001(4001, "缺少必要文件:%s"),
+    FAILURE_CODE_4002(4002, "文件不存在:%s"),
 
 
     FAILURE_CODE_5001(5001, "modeldata.json为空"),

+ 38 - 0
4dkankan-common-utils/src/main/java/com/fdkankan/common/constant/FileSizeUnitType.java

@@ -0,0 +1,38 @@
+package com.fdkankan.common.constant;
+
+/**
+ * 文件业务类型
+ */
+public enum FileSizeUnitType {
+
+    B("B"),
+    KB("KB"),
+    MB("MB"),
+    GB("GB"),
+    TB("TB"),
+    PB("PB")
+    ;
+
+    private String code;
+
+    private FileSizeUnitType(String code) {
+        this.code = code;
+    }
+
+    public String code() {
+        return code;
+    }
+
+    public static FileSizeUnitType get(String code){
+        FileSizeUnitType[] values = FileSizeUnitType.values();
+        String enumValue = null;
+        for(FileSizeUnitType eachValue : values){
+            enumValue = eachValue.code();
+            if(enumValue.equals(code)){
+                return eachValue;
+            }
+        }
+        return null;
+    }
+
+}

+ 41 - 0
4dkankan-common-utils/src/main/java/com/fdkankan/common/util/FileSizeUtil.java

@@ -1,8 +1,13 @@
 package com.fdkankan.common.util;
 
+import com.fdkankan.common.constant.FileSizeUnitType;
+
 import java.io.File;
 import java.io.FileInputStream;
+import java.math.BigDecimal;
 import java.text.DecimalFormat;
+import java.util.HashMap;
+import java.util.Objects;
 
 public class FileSizeUtil {
 
@@ -115,6 +120,42 @@ public class FileSizeUtil {
     }
 
     /**
+     * 文件大小单位转换
+     * @param size 原始大小,单位B
+     * @param unit 需要转换的目标单位 B KB MB GB TB PB
+     * @return
+     */
+    public static Integer convert(long size, String unit) throws Exception {
+        FileSizeUnitType fileSizeUnitType = FileSizeUnitType.get(unit);
+        if(Objects.isNull(fileSizeUnitType)){
+            throw new Exception("单位错误!");
+        }
+        if(size == 0){
+            return 0;
+        }
+        BigDecimal bigDecimal = new BigDecimal(size);
+        long divisor = 1L;
+        switch (fileSizeUnitType){
+            case KB:
+                divisor = 1024L;
+                break;
+            case MB:
+                divisor = 1048576L;
+                break;
+            case GB:
+                divisor = 1073741824L;
+                break;
+            case TB:
+                divisor = 1099511627776L;
+                break;
+            case PB:
+                divisor = 1125899906842624L;
+                break;
+        }
+        return bigDecimal.divide(new BigDecimal(divisor)).setScale(0, BigDecimal.ROUND_UP).intValue();
+    }
+
+    /**
      * 转换文件大小,指定转换的类型
      */
     public static double formetFileSize(long fileS, int sizeType) {