如何将文件大小人类可读格式转换为 Java 中的字节大小?

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

我基本上需要做相反的事情: How can I convert byte size into a human-readable format in Java?
输入:10.0MB
输出:10000000

你可以像这样使用枚举

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

基于 HariHaravelan 的

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

用作
long bytes = (long) (10.0 * Unit.multiplier("MB"))


对于科学单位(KB = 1000),替换enum内的第一行(数字之间的下划线被Java忽略):

public enum Unit {
    B(1), KB(1_000), MB(1_000_000), GB((1_000_000_000)
    ... rest as above

可以根据需要添加更多单位 - 最多 long 的限制,如果需要更多,可以将 multiplier 声明更改为 BigDecimaldouble 根据使用 case/requirement.