博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 获取文件大小
阅读量:7209 次
发布时间:2019-06-29

本文共 1464 字,大约阅读时间需要 4 分钟。

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

有两种方式

方式一:使用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()方法

转载地址:http://numum.baihongyu.com/

你可能感兴趣的文章
计算机网络常见英文缩写
查看>>
Esper epl语句实验
查看>>
使用phpize建立php扩展(Cannot find config.m4)
查看>>
【TensorFlow】CNN
查看>>
redis cli命令
查看>>
C#中委托和事件的区别
查看>>
数据库操作
查看>>
CLIPS
查看>>
HBase中数据的多版本特性潜在的意外
查看>>
僵还是老的la,看myeclipse的spring mvc3 scaffolding 完胜sts
查看>>
网上开店进货渠道大参考
查看>>
经典语录
查看>>
【配置文件】log4j是什么log4j
查看>>
xsd验证允许空值
查看>>
图灵成立七周年——经典回顾
查看>>
#周末课堂# 赵扬老师 Android系列课程【ListView完全解析、Memory in Android】(火热报名中~~~)...
查看>>
【改进】C# WinForm捕获全局异常 SamWang
查看>>
HashMap的使用方法及注意事项
查看>>
高清接口芯片---gv7600、sii9135
查看>>
相机标准之onvif---开放型网络视频接口论坛onvif 简介
查看>>