Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
like image 820
Joel Rosenberg Avatar asked Dec 13 '11 20:12

Joel Rosenberg


2 Answers

Apache commons provides constants in the FileUtils class, like

  • FileUtils.ONE_MB
  • FileUtils.ONE_GB
  • ...

source : https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/FileUtils.html

Their definition of a KB is based on 1024 bytes, (a MB is KB², and so long).

like image 64
Xavier Portebois Avatar answered Oct 07 '22 06:10

Xavier Portebois


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. :)

like image 43
Fabian Barney Avatar answered Oct 07 '22 06:10

Fabian Barney