使用Java获取文件大小时,必须使用long类型来保存大小,如果一个返回文件大小的方法返回的不是long类型,如int,则会存在范围溢出的问题,尤其是对大文件。
Java获取文件大小有两个方法:
1.使用File类的length方法
File f= new File("D:\test.pdf");
if (f.exists() && f.isFile()){
long size = f.length();
}
2.使用FileChannel
FileChannel fc= null;
try {
File f= new File("D:\test.pdf");
if (f.exists() && f.isFile()){
FileInputStream fis= new FileInputStream(f);
fc= fis.getChannel();
long size = fc.size();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (null!=fc)){
try{
fc.close();
}catch(IOException e){
}
}
}