Last active
September 28, 2024 17:58
-
-
Save SatyaSnehith/2441b85c8f945f2cf024fb7e6971d869 to your computer and use it in GitHub Desktop.
Convert Bytes to KB, MB, GB, TB - java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
nice code! change 1000 to 1024
The long n = 1000
is a bug in my eyes. it should be 1024 instead.
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 "";
}
@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
niiice