21 获取文件大小的方法
package com.hikvision.java.file.filesize;/* * Project: HbaseTest * Address: http://www.hikvision.com * Date: 2016/10/31 10:02 * Description: This content is limited to use in Hikivision Research Institude, forwarding is prohibited. * * Copyright (c) 2016. 2002-2016@Hangzhou Hikvision Digital Technology Co., Ltd. All Right Reservered. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** 获取文件大小,的三种方式 字节,KB ,MB : bytes,kilobytes,megabytes */ public class ObtainFileSize { public static final Logger LOG= LoggerFactory.getLogger(ObtainFileSize.class); public static void main(String[] args) { String filePath="F:\\test\\fileSize.txt"; if(!new File(filePath).exists()){ }else{ long fileSize=getFileSizeMethod1(filePath); LOG.info("the size of {} is {} bytes",filePath,fileSize); LOG.info("the size of {} is {} MB",filePath,byteToMB(fileSize)); } } /** * @param FilePath 获取文件大小 单位字节 * @return */ public static long getFileSizeMethod1(String FilePath){ return new File(FilePath).length(); } /** * * @param FilePath 获取文件大小 单位字节 最大2G * @return * @throws IOException */ public static int getFileSizeMethod2(String FilePath) throws IOException { return new FileInputStream(FilePath).available(); } /** * * @param FilePath 获取文件大小 单位字节 * @return * @throws IOException */ public static long getFileSizeMethod3(String FilePath) throws IOException { return new FileInputStream(FilePath).getChannel().size(); } /** * 字节转成KB * @param size * @return */ public static double byteToKB(long size){ return size/1024.0; } public static double byteToMB(long size){ return size/(1024*1024.0); } }
本文来自博客园,作者:life_start,转载请注明原文链接:https://www.cnblogs.com/yangh2016/p/6015125.html