add unit type for bytes

This commit is contained in:
2023-03-17 16:53:34 +01:00
parent 686e3edd60
commit 359c17bf29
6 changed files with 150 additions and 31 deletions

View 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;
}
}