In a file-processing system, it is easy to get the size out of some system's own method, the problem is that the size is often just a byte B.
If you want to convert this byte number to a KB, MB, GB final rendering to the user, it involves the arithmetic operation of dividing and taking the remainder.
Here's how:
public static String getprintsize (long size) {///If the number of bytes is less than 1024, it is directly in B, otherwise except for 1024, the latter 3 bits are too little meaningless if (size < 1024x768) {return String.valueof (size) + "B";} else {size = size/1024;} If the original number of bytes is less than 1024 after 1024, then it can be directly in kilobytes//because it has not yet reached the time to use the other unit//and then the if (size < string.valueof) {return + (size) + " KB ";} else {size = size/1024;} if (Size < 1024) {//Because if in MB, the last 1 decimal places are to be retained,//Therefore, multiply this number by 100 and then take the remainder size = size * 100;return string.valueof ((size/100)) + ". "+ string.valueof ((size%)) +" MB ";} else {//otherwise if you want to do the same in GB, except for 1024, size = size * 100/1024;return string.valueof ((size/100)) + "." + string.valueof ((size%)) + "GB";}}
In the main function call a few bytes B, to test:
Package Filesize;public class Filesizetest {public static String getprintsize (long size) {///If the number of bytes is less than 1024, it is directly in units B. Otherwise, except for 1024, the latter 3 is too little meaningless if (size < 1024x768) {return string.valueof (size) + "B";} else {size = size/1024;} If the original number of bytes is less than 1024 after 1024, then it can be directly in kilobytes//because it has not yet reached the time to use the other unit//and then the if (size < string.valueof) {return + (size) + " KB ";} else {size = size/1024;} if (Size < 1024) {//Because if in MB, the last 1 decimal places are to be retained,//Therefore, multiply this number by 100 and then take the remainder size = size * 100;return string.valueof ((size/100)) + ". "+ string.valueof ((size%)) +" MB ";} else {//otherwise if you want to do the same in GB, except for 1024, size = size * 100/1024;return string.valueof ((size/100)) + "." + string.valueof ((size%)) + "GB";}} public static void Main (string[] args) {System.out.println (Getprintsize (200)); System.out.println (Getprintsize (200000)); System.out.println (Getprintsize (200000000)); System.out.println (Getprintsize (2000000000));}}
Running results such as:
"Java" converts bytes B to KB, MB, GB method