'How can I convert file size human-readable format into byte size in Java?
I basically need to do the opposite of this:
How can I convert byte size into a human-readable format in Java?
Input: 10.0MB
Outpt: 10000000
Solution 1:[1]
Based on HariHaravelan's answer
public enum Unit {
B(1), KB(1024), MB(1024*1024), GB((1024L*1024L*1024L)
;
private final long multiplier;
private Unit(long multiplier) {
this.multiplier = multiplier;
}
// IllegalArgumentException if the symbol is not recognized
public static long multiplier(String symbol) throws IllegalArgumentException {
return Unit.valueOf(symbol.toUpperCase()).multiplier;
}
}
to be used as inlong bytes = (long) (10.0 * Unit.multiplier("MB"))
for scientific units (KB = 1000), replace first line inside the enum (underscore between digits are ignored by Java):
public enum Unit {
B(1), KB(1_000), MB(1_000_000), GB((1_000_000_000)
... rest as above
More units can be added as needed - up to the limit of long, if more are required, the multiplier declaration can be changed to BigDecimal or double according use case/requirement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
