Last active
September 15, 2021 16:53
-
-
Save daanta-real/c931d1846147657d692dbc3c7cfa30c4 to your computer and use it in GitHub Desktop.
Get the formatted text of a file size
This file contains hidden or 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
// 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"; | |
} |
This file contains hidden or 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
// 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