1. 程式人生 > >java 根據圖片地址獲取到圖片的大小,單位kb或者Mb

java 根據圖片地址獲取到圖片的大小,單位kb或者Mb

  1. /** 
  2.      * byte(位元組)根據長度轉成kb(千位元組)和mb(兆位元組) 
  3.      *  
  4.      * @param bytes 
  5.      * @return 
  6.      */  
  7.     public static String bytes2kb(long bytes) {  
  8.         BigDecimal filesize = new BigDecimal(bytes);  
  9.         BigDecimal megabyte = new BigDecimal(1024 * 1024);  
  10.         float returnValue = filesize.divide(megabyte, 2
    , BigDecimal.ROUND_UP)  
  11.                 .floatValue();  
  12.         if (returnValue > 1)  
  13.             return (returnValue + "MB");  
  14.         BigDecimal kilobyte = new BigDecimal(1024);  
  15.         returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)  
  16.                 .floatValue();  
  17.         return
     (returnValue + "KB");  
  18.     } 
/**
	* @Title: pathSize 
	* @param @param imgPath
	* @param @return  根據圖片地址返回圖片大小kb或者 Mb   
	* @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);
	}