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.Objects;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 public class FileSize {
35
36 private final static String LENGTH_PART = "([0-9]+)";
37 private final static int DOUBLE_GROUP = 1;
38
39 private final static String UNIT_PART = "(|kb|mb|gb)s?";
40 private final static int UNIT_GROUP = 2;
41
42 private static final Pattern FILE_SIZE_PATTERN = Pattern.compile(LENGTH_PART + "\\s*" + UNIT_PART,
43 Pattern.CASE_INSENSITIVE);
44
45 static public final long KB_COEFFICIENT = 1024;
46 static public final long MB_COEFFICIENT = 1024 * KB_COEFFICIENT;
47 static public final long GB_COEFFICIENT = 1024 * MB_COEFFICIENT;
48
49 final long size;
50
51 public FileSize(long size) {
52 this.size = size;
53 }
54
55 public long getSize() {
56 return size;
57 }
58
59 static public FileSize valueOf(String fileSizeStr) {
60 Matcher matcher = FILE_SIZE_PATTERN.matcher(fileSizeStr);
61
62 long coefficient;
63 if (matcher.matches()) {
64 String lenStr = matcher.group(DOUBLE_GROUP);
65 String unitStr = matcher.group(UNIT_GROUP);
66
67 long lenValue = Long.valueOf(lenStr);
68 if (unitStr.equalsIgnoreCase("")) {
69 coefficient = 1;
70 } else if (unitStr.equalsIgnoreCase("kb")) {
71 coefficient = KB_COEFFICIENT;
72 } else if (unitStr.equalsIgnoreCase("mb")) {
73 coefficient = MB_COEFFICIENT;
74 } else if (unitStr.equalsIgnoreCase("gb")) {
75 coefficient = GB_COEFFICIENT;
76 } else {
77 throw new IllegalStateException("Unexpected " + unitStr);
78 }
79 return new FileSize(lenValue * coefficient);
80 } else {
81 throw new IllegalArgumentException("String value [" + fileSizeStr + "] is not in the expected format.");
82 }
83 }
84
85 @Override
86 public String toString() {
87 long inKB = size / KB_COEFFICIENT;
88
89 if (inKB == 0)
90 return size + " Bytes";
91
92 long inMB = size / MB_COEFFICIENT;
93 if (inMB == 0) {
94 return inKB + " KB";
95 }
96
97 long inGB = size / GB_COEFFICIENT;
98 if (inGB == 0) {
99 return inMB + " MB";
100 }
101
102 return inGB + " GB";
103
104 }
105
106 @Override
107 public boolean equals(Object o) {
108 if (this == o)
109 return true;
110 if (o == null || getClass() != o.getClass())
111 return false;
112 FileSize fileSize = (FileSize) o;
113 return size == fileSize.size;
114 }
115
116 @Override
117 public int hashCode() {
118 return Objects.hashCode(size);
119 }
120 }