add unit type for bytes
This commit is contained in:
32
pdb-utils/src/main/java/org/lucares/utils/HumanBytes.java
Normal file
32
pdb-utils/src/main/java/org/lucares/utils/HumanBytes.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package org.lucares.utils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class HumanBytes {
|
||||
|
||||
public static final long KB = 1024;
|
||||
|
||||
public static final long MB = KB * 1024;
|
||||
|
||||
public static final long GB = MB * 1024;
|
||||
|
||||
public static final long TB = GB * 1024;
|
||||
|
||||
public static final long PB = TB * 1024;
|
||||
|
||||
public static final long EB = TB * 1024;
|
||||
|
||||
public static String toHumanBytes(final long bytes) {
|
||||
final List<String> powers = List.of("bytes", "KB", "MB", "GB", "TB", "PB", "EB");
|
||||
|
||||
int power = 1;
|
||||
String result = String.format("%d bytes", bytes);
|
||||
while (bytes >= Math.pow(1024, power) && power < powers.size()) {
|
||||
result = String.format("%.3f", bytes / Math.pow(1024, power));
|
||||
result = result.replaceAll("\\.?0*$", "");
|
||||
result = result + " " + powers.get(power);
|
||||
power = power + 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user