Java中获取文件大小的方法
2015-12-14
最近做了一个往后台传图片的功能,HttpClient弃用的应对方法在此不表。传图片时有一个需求是同时把文件的大小传给后台(话说这事儿不得是后台自己处理文件的大小吗?),主要说说Android(Java)中如何获取文件大小吧。
Java中获取文件大小的方法有不少,但是有个坑需要注意,有些方法返回的结果是int型,我们知道Integer.MAX_VALUE
= 2147483647 (0x7fffffff),这个值大约等于2GB,所以对于2GB以下的文件来说,利用返回int型的方法来获取文件大小是没问题的,例如FileInputStream
类的实例方法available
。但是,我们不能给自己或者他人留下一个坑对吧,即便是你加了一条很显眼的注释来警告,所以我们一律只考虑用返回long型的方法来获取文件大小。
使用File类的实例方法length
public static long calculateFileSize(String filePath) {
File f = new File(filePath);
if (f.exists() && f.isFile()) {
return f.length();
} else {
Log.w(TAG, "file does not exist or is not a file");
}
}
使用FileChannel类的实例方法size
public static long calculateFileSize(String filePath) {
FileChannel fc = null;
FileInputStream fis = null;
try {
File f = new File(filePath);
if (f.exists() && f.isFile()) {
FileInputStream fis = new FileInputStream(f);
fis.getChannel();
return fc.size();
} else {
Log.w(TAG, "file does not exist or is not a file");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fc != null) {
try {
fc.close();
} catch(IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}

除非另有声明,本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。