获取文件大小Byte、KB、MB、GB、TB单位自动转换
下面这个是直接获取Byte(字节大小)
/**
* 获取文件的大小(Byte)
* @param file 文件
* @return 文件的大小 若文件不存在或者不是文件就返回null
*/
public static Long getByteSize(File file) {
if (file.exists() && file.isFile()) {
return file.length();
}
return null;
}
这一个是标题说的那种情况、会自动判断文件大小生成文件达到的最大单位为单位的、大小为小数点后三位、四舍五入的字符串(方便存入数据库中)
/**
* 获取文件的大小(返回到达的最高单位)
* 比如:1024Byte就不再用Byte
* 直接返回1KB
* 返回值精确到小数点后3位
* @param file 文件
* @return 文件的大小 若文件不存在或者不是文件就返回null
*/
public static String getSize(File file) {
long size = getByteSize(file);
double s = (double) size;
String unit;
if (size != -1L) {
int l;
if (size < 1024L) {
l = 0;
} else if (size < 1024L *