Java 计算文件的信息没有C,C++的方便了,下面介绍几个常用求文件大小的方法:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TestFileSize {
//方法一
private static Long getReportFileSize(String filePath) {
Long size = 0L;
File f = new File(filePath);
if (f.exists() && f.isFile()) {
size = f.length();
System.out.println("方法一:\n File:"+ filePath + "\nsize:" + size + "\n");
}
else {
System.out.print("\nfile doesn't exist or is not a file\n");
}
return size;
}
//方法二
private static int getReportFileSize2(String filePath) {
File f= new File(filePath);
FileInputStream fis= null;
int size = 0;
if (f.exists() && f.isFile()) {
try {
fis= new FileInputStream(f);
size = fis.available();
System.out.println("方法二:\nFile:"+ filePath + "\nsize:" + size + "\n");
fis.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
System.out.print("\nfile doesn't exist or is not a file\n");
}
return size;
}
//方法三
private static void getReportFileSize3(String filePath) {
File f= new File(filePath);
FileInputStream fis= null;
FileChannel fc = null;
Long size = 0L;
if (f.exists() && f.isFile()) {
try {
fis= new FileInputStream(f);
fc = fis.getChannel();
size = fc.size();
System.out.println("方法三:\nFile:"+ filePath + "\n asize:" + size + "\n");
fis.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
System.out.print("\nfile doesn't exist or is not a file\n");
}
}
public static void main(String[] args) {
String filePath = "D:\\Downloads\\FlashFXP.tar";
getReportFileSize(filePath);
getReportFileSize2(filePath);
getReportFileSize3(filePath);
}
}
可能用C++习惯了总感觉用java在获取文件时间,大小等一些文件信息的时候没有C++方便。
方法一最简洁,效率最高,直接用文件File指针,length函数返回文件或者文件夹的大小。
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
注意管道文件的时候返回文件的大小为0L方法二用FileInputStream fis,利用available函数来获取文件的大小, 注意这个函数返回大小是整形,所以所能计算最大的文件的大小只有2G左右,效率相对也较低。
方法三用FileInputStream fis,利用getChannel函数来获取文件的大小,不存在上面函数的问题