目前Java获取文件大小的方法有两种:
1、通过file的length()方法获取;
2、通过流式方法获取;
通过流式方法又有两种,分别是旧的java.io.*中FileInputStream的available()方法和新的java..nio.*中的FileChannel
length方法:
1 /** 2 * 获取文件大小(字节byte) 3 * 方式一:file.length() 4 */ 5 public void getFileLength(File file){ 6 long fileLength = 0L; 7 if(file.exists() && file.isFile()){ 8 fileLength = file.length(); 9 } 10 System.out.println("文件"+file.getName()+"的大小为:"+fileLength+"byte"); 11 }
available方法:
1 /** 2 * 获取文件大小 3 * 方式二:FileInputStream.available() 4 * 注意:int类型所能表示的最大值2^31-1,如果文件的大小超过了int所能表示的最大值结果会有误差 5 * @throws IOException 6 */ 7 public void getFileLength2(File file) throws IOException{ 8 int length = 0; 9 FileInputStream fis = null; 10 if(file.exists() && file.isFile()){ 11 fis = new FileInputStream(file); 12 length = fis.available(); 13 } 14 System.out.println("文件"+file.getName()+"的大小为:"+length+"byte"); 15 }
FileChannel方法:
1 /** 2 * 获取文件大小 3 * 方式一:FileInputStream.getChannel() 4 * @throws IOException 5 */ 6 public void getFileLength3(File file) throws IOException{ 7 FileInputStream fis = null; 8 FileChannel fileChannel = null; 9 if(file.exists() && file.isFile()){ 10 fis = new FileInputStream(file); 11 fileChannel = fis.getChannel(); 12 } 13 System.out.println("文件"+file.getName()+"的大小为:"+fileChannel.size()+"byte"); 14 }