Skip to content

Instantly share code, notes, and snippets.

@daanta-real
Last active September 15, 2021 16:53
Show Gist options
  • Save daanta-real/c931d1846147657d692dbc3c7cfa30c4 to your computer and use it in GitHub Desktop.
Save daanta-real/c931d1846147657d692dbc3c7cfa30c4 to your computer and use it in GitHub Desktop.
Get the formatted text of a file size
// What you input: file size (long or its sub type)
// What you get: formatted text of a file size.
// ex) 23.44 MBytes, 15.20 TBytes, 1,015 Bytes, ...
public static String getFileSizeFormatedTxt(long fileSize) {
// Unit size infoes
Object[][] bytes = {
{1099511627776L, "T"},
{1073741824L , "G"},
{1048576L , "M"},
{1024L , "k"}
};
// Make the string. "XX.XX G", "XX.XX M", ...
String s = "";
for(Object[] o: bytes)
if(fileSize >= (long)o[0]) {
s = String.format(
"%,.2f %s",
(float)fileSize / (long)o[0],
o[1]
);
break;
}
if(s == "") s = String.format("%,d ", fileSize);
// Retrun the result
return s + "Bytes";
}
// Returns the size string using kB, MB, Gb, ... format
private static String getFileSizeFormatedTxt(long fileSize) {
Object[][] sizeInfoes = { {1099511627776L, "T"}, {1073741824L, "G"}, {1048576L, "M"}, {1024L, "k"} };
String s = "";
for(Object[] o: sizeInfoes) if(fileSize >= (long)o[0]) {
s = String.format("%,.2f %s", (float)fileSize / (long)o[0], o[1] );
break;
}
if(s == "") s = String.format("%,d ", fileSize);
return s + "Bytes";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment