简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM