package com.shm.wechat.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.channels.FileChannel; import com.shm.wechat.utils.Constant; /** * 文件操作工具类 * */ public class FileUtil { public static void main(String[] args) { System.out.println(getFileSize("E:\\tomcat.zip")); } /** * 计算文件大小 * @param filePath * @return 单位是byte */ public static long getFileSize(String filePath) { long size = 0; FileInputStream fis= null; FileChannel fc= null; try { File f = new File(filePath); if (f.exists() && f.isFile()){ fis= new FileInputStream(f); fc= fis.getChannel(); size = fc.size(); }else{ Constant.LOGGER.error("{},file doesn't exist or is not a file", filePath); } } catch (FileNotFoundException e) { Constant.LOGGER.error("文件大小检查发生异常,{}", e.getMessage()); } catch (IOException e) { Constant.LOGGER.error("文件大小检查发生异常,{}", e.getMessage()); } finally { if (null!=fc){ try{ fc.close(); }catch(IOException e){ Constant.LOGGER.error("FileChannel资源关闭发生异常,{}", e.getMessage()); } } if (null!=fis){ try{ fis.close(); }catch(IOException e){ Constant.LOGGER.error("FileInputStream资源关闭发生异常,{}", e.getMessage()); } } } return size; } }