Search code examples
javatimeenumsfilesize

Is there a Java enum for filesize units that's equivalent to java.util.concurrent.TimeUnit?


I've always liked the readability of assignments that used TimeUnit like so:

long timePeriodInMillis = TimeUnit.MINUTES.toMillis( 53 );

Over something like:

long timePeriodInMillis = 53 * 60 * 1000;

Is there an equivalent enum I can use for filesize units? Something like

long maxBits = FilesizeUnit.MEGABYTES.toBits( 11 );

Solution

  • I've done exactly sth like this half a year ago just for fun inspired by TimeUnit enum.

    I will upload it at GitHub tomorrow. It contains two enums: BitUnit and ByteUnit. Both also support converting between each other. ByteUnit has support for 2-based Prefixes as well for 10-based Prefixes. (Enum constants and methods in ByteUnit use IEC 80000-13 terminology for the prefixes.)

    Usage looks like this:

    System.out.println(BitUnit.KBIT.toKiB(16000));
    
    System.out.println(ByteUnit.GIB.toMB(1));
    System.out.println(ByteUnit.GIB.toMiB(1));
    System.out.println(ByteUnit.GB.toMB(1));
    System.out.println(ByteUnit.GB.toMiB(1));
    

    ... and prints out:

    1953.125
    
    1073.741824
    1024.0
    1000.0
    953.67431640625
    

    For convertion methods between Bits and Bytes you've overloaded methods to specify a word size other than 8 bits per byte. Hope you can wait until tomorrow.


    EDIT

    Here you are: https://github.com/fabian-barney/Utils

    Do not blame me for the directory structure - I am still not familar with Git yet. :)