1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.util;
15
16 import java.util.regex.Matcher;
17 import java.util.regex.Pattern;
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 public class FileSize {
34
35 private final static String LENGTH_PART = "([0-9]+)";
36 private final static int DOUBLE_GROUP = 1;
37
38 private final static String UNIT_PART = "(|kb|mb|gb)s?";
39 private final static int UNIT_GROUP = 2;
40
41 private static final Pattern FILE_SIZE_PATTERN = Pattern.compile(LENGTH_PART + "\\s*" + UNIT_PART,
42 Pattern.CASE_INSENSITIVE);
43
44 static public final long KB_COEFFICIENT = 1024;
45 static public final long MB_COEFFICIENT = 1024 * KB_COEFFICIENT;
46 static public final long GB_COEFFICIENT = 1024 * MB_COEFFICIENT;
47
48 final long size;
49
50 public FileSize(long size) {
51 this.size = size;
52 }
53
54 public long getSize() {
55 return size;
56 }
57
58 static public FileSize valueOf(String fileSizeStr) {
59 Matcher matcher = FILE_SIZE_PATTERN.matcher(fileSizeStr);
60
61 long coefficient;
62 if (matcher.matches()) {
63 String lenStr = matcher.group(DOUBLE_GROUP);
64 String unitStr = matcher.group(UNIT_GROUP);
65
66 long lenValue = Long.valueOf(lenStr);
67 if (unitStr.equalsIgnoreCase("")) {
68 coefficient = 1;
69 } else if (unitStr.equalsIgnoreCase("kb")) {
70 coefficient = KB_COEFFICIENT;
71 } else if (unitStr.equalsIgnoreCase("mb")) {
72 coefficient = MB_COEFFICIENT;
73 } else if (unitStr.equalsIgnoreCase("gb")) {
74 coefficient = GB_COEFFICIENT;
75 } else {
76 throw new IllegalStateException("Unexpected " + unitStr);
77 }
78 return new FileSize(lenValue * coefficient);
79 } else {
80 throw new IllegalArgumentException("String value [" + fileSizeStr + "] is not in the expected format.");
81 }
82 }
83
84 @Override
85 public String toString() {
86 long inKB = size / KB_COEFFICIENT;
87
88 if (inKB == 0)
89 return size + " Bytes";
90
91 long inMB = size / MB_COEFFICIENT;
92 if (inMB == 0) {
93 return inKB + " KB";
94 }
95
96 long inGB = size / GB_COEFFICIENT;
97 if (inGB == 0) {
98 return inMB + " MB";
99 }
100
101 return inGB + " GB";
102
103 }
104 }