java 获取文件大小

Java 中如何获取文件的大小呢?

有两种方式

方式一:使用File 的length()方法;

方式二:使用FileInputStream的available()方法;

实例:

Java代码   收藏代码
  1. @Test  
  2.     public void test01() throws IOException {  
  3.         String filepath = "d:\\bin\\pushpoxy-0.0.1-SNAPSHOT.jar";  
  4.         System.out.println("File has " + new File(filepath).length()+ " bytes");  
  5.         FileInputStream fis = null;    
  6.         fis = new FileInputStream(filepath);    
  7.         System.out.println("File has " + fis.available() + " bytes");  
  8.   
  9.     }  

运行结果 :

File has 29061936 bytes

File has 29061936 bytes

其实这两个方法时有区别的;

File 的length()方法 是获取文件所占硬盘空间大小;

FileInputStream的available()方法是还有多少字节可以读取.

available()方法的说明如下:

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. 

 

我们把上面的程序稍微修改一下:

Java代码   收藏代码
  1. @Test  
  2.     public void test01() throws IOException {  
  3.         String filepath = "d:\\bin\\pushpoxy-0.0.1-SNAPSHOT.jar";  
  4.         System.out.println("File has " + new File(filepath).length()+ " bytes");  
  5.         FileInputStream fis = null;    
  6.         fis = new FileInputStream(filepath);  
  7.         byte[]bytes=new byte[10];  
  8.         fis.read(bytes);  
  9.         System.out.println("File has " + fis.available() + " bytes");  
  10.         fis.skip(-10);  
  11.         System.out.println("File has " + fis.available() + " bytes");  
  12.   
  13.     }  

 执行结果如下:

File has 29061936 bytes

File has 29061926 bytes

File has 29061936 bytes

 

总结:获取文件大小时建议使用File 的length()方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值