Skip to content

Instantly share code, notes, and snippets.

@SatyaSnehith
Last active September 28, 2024 17:58
Show Gist options
  • Save SatyaSnehith/2441b85c8f945f2cf024fb7e6971d869 to your computer and use it in GitHub Desktop.
Save SatyaSnehith/2441b85c8f945f2cf024fb7e6971d869 to your computer and use it in GitHub Desktop.
Convert Bytes to KB, MB, GB, TB - java
public class Converter{
static long kilo = 1024;
static long mega = kilo * kilo;
static long giga = mega * kilo;
static long tera = giga * kilo;
public static void main(String[] args) {
for (String arg: args) {
try {
System.out.println(getSize(Long.parseLong(arg)));
} catch(NumberFormatException e) {
System.out.println(arg + " is not a long");
}
}
}
public static String getSize(long size) {
String s = "";
double kb = (double)size / kilo;
double mb = kb / kilo;
double gb = mb / kilo;
double tb = gb / kilo;
if(size < kilo) {
s = size + " Bytes";
} else if(size >= kilo && size < mega) {
s = String.format("%.2f", kb) + " KB";
} else if(size >= mega && size < giga) {
s = String.format("%.2f", mb) + " MB";
} else if(size >= giga && size < tera) {
s = String.format("%.2f", gb) + " GB";
} else if(size >= tera) {
s = String.format("%.2f", tb) + " TB";
}
return s;
}
}
@Cranked
Copy link

Cranked commented Jun 26, 2022

I hope that it would be more useful
public String getFileSize(long size, int round) {
try {
if (size <= 0)
return "0";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return String.format("%." + round + "f", size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
} catch (Exception e) {
System.out.println(e.toString());
}
return "";
}

@killemov
Copy link

killemov commented May 2, 2024

@Cranked Nice and clean ... but expensive! Do NOT use in (tight) loops.

Mixed alternative:

public class ByteUnitFormatter {
  private static final int THRESHOLD = 1024; // You could use 2048, 4096 or 8192 for greater precision / lower unit.

  private static final String[] UNITS = new String[]{ "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

  public static void main( String[] args ) {
    for( String arg : args ) {
      try {
        System.out.println( format( Long.parseLong( arg ), 2 ) );
      } catch (NumberFormatException e) {
        System.out.println( arg + " is not a long" );
      }
    }
  }

  public static String format( double size, int decimals ) {
    size = size < 0 ? 0 : size;
    int u;
    for( u = 0; u < UNITS.length - 1 && size >= THRESHOLD; ++u ) {
      size /= 1024;
    }
    return String.format( "%." + decimals + "f %s", size, UNITS[ u ] );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment