Home > database >  How can I convert file size human-readable format into byte size in Java?
How can I convert file size human-readable format into byte size in Java?

Time:03-06

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

CodePudding user response:

You can use an enum like this

public static void main(String[] args) {

    System.out.println(10 * UNIT.calculateBytes("MB"));
}

enum UNIT {
    B(1000), KB(1000), MB(1000), GB(1000), TB(1000);

    private int timesThanPreviousUnit;

    UNIT(int timesThanPreviousUnit) {
        this.timesThanPreviousUnit = timesThanPreviousUnit;
    }

    public static long calculateBytes(String symbol) {
        long inBytes = 1;
        UNIT inputUnit = UNIT.valueOf(symbol);
        UNIT[] UNITList = UNIT.values();

        for (UNIT unit : UNITList) {
            if (inputUnit.equals(unit)) {
                return inBytes;
            }
            inBytes *= unit.timesThanPreviousUnit;
        }
        return inBytes;
    }
}

CodePudding user response:

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 in
long 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.

  • Related