Java gets the size of the image according to the image address, in KB or MB

Time:2020-10-18

/**
* byte is converted into KB and MB according to length
     * 
     * @param bytes
     * @return
     */ 
    public static String bytes2kb(long bytes) { 
        BigDecimal filesize = new BigDecimal(bytes); 
        BigDecimal megabyte = new BigDecimal(1024 * 1024); 
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP) 
                .floatValue(); 
        if (returnValue > 1) 
            return (returnValue + “MB”); 
        BigDecimal kilobyte = new BigDecimal(1024); 
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP) 
                .floatValue(); 
        return (returnValue + “KB”); 
    }

/** 

* @Title: pathSize  

 

*@param imgPath 

 

*@Return returns the image size KB or MB according to the image address

* @return String   

 * @throws  

* @add (default no) 

*/ 

public String pathSize(String imgPath) {  

  File file = new File(imgPath); 

   FileInputStream fis; 

   int fileLen = 0;  

  try {   

    fis = new FileInputStream(file);

    fileLen = fis.available(); 

   } catch (FileNotFoundException e) {  

     e.printStackTrace(); 

   } catch (IOException e) { 

      e.printStackTrace(); 

   }  

   return bytes2kb(fileLen); 

}