Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Human readable size units (file sizes) for scala code (like Duration)

Tags:

scala

Are there any libraries that provide an object/class with implicits conversions (from Int, Long, Float) for human readable file size units (like Duration).

With Duration you can do this:

11.millis
1.5.minutes
10.hours

I wonder if there is some library that would allow me to do:

1.gibabyte
1024.megabytes
10.gibibytes
10.GB
50.GiB

I know I could implement this myself, but I'm trying to not reinvent the wheel.

like image 357
Onilton Maciel Avatar asked Dec 24 '22 08:12

Onilton Maciel


1 Answers

Squants is a good solution, especially if you need more than just the human readable byte size conversion from the lib, but another possibility is to use this simple 4-line solution ported from an old SO java solution. You may not need the ZB and YB today, but maybe in the future ;)

  /**
    * @see https://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
    * @see https://en.wikipedia.org/wiki/Zettabyte
    * @param fileSize Up to Exabytes
    * @return
    */
  def humanReadableByteSize(fileSize: Long): String = {
    if(fileSize <= 0) return "0 B"
    // kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta
    val units: Array[String] = Array("B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    val digitGroup: Int = (Math.log10(fileSize)/Math.log10(1024)).toInt
    f"${fileSize/Math.pow(1024, digitGroup)}%3.3f ${units(digitGroup)}"
  }
like image 178
user4955663 Avatar answered Mar 22 '23 22:03

user4955663