Converting KB to MB, GB, TB dynamically

后端 未结 10 1956
广开言路
广开言路 2020-12-14 18:24
public String size(int size){
    String hrSize = \"\";
    int k = size;
    double m = size/1024;
    double g = size/1048576;
    double t = size/1073741824;

            


        
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 19:19

    public class FileSizeCalculator {
    
        String[] fileSizeUnits = {"bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
    
        public static void main(String[] args) {
            FileSizeCalculator fs = new FileSizeCalculator();
            String properFileSize = fs.calculateProperFileSize(2362232012l);
            System.out.println("Proper file size: " + properFileSize);
        }
    
        public String calculateProperFileSize(long noOfBytes){
            String sizeToReturn = "";// = FileUtils.byteCountToDisplaySize(bytes), unit = "";
            double bytes = noOfBytes;
            int index = 0;
            for(index = 0; index < fileSizeUnits.length; index++){
                if(bytes < 1024){
                    break;
                }
                bytes = bytes / 1024;
            }
            sizeToReturn = String.valueOf(bytes) + " " + fileSizeUnits[index];
            return sizeToReturn;
        }
    }
    

    Just add more file unit (if any missing), and you will see unit size up to that unit (if your file has that much length)

提交回复
热议问题