java 获取文件大小
程序员文章站
2024-02-26 14:53:22
...
java 中如何获取文件的大小呢?
有两种方式
方式一:使用File 的length()方法;
方式二:使用FileInputStream的available()方法;
实例:
@Test
public void test01() throws IOException {
String filepath = "d:\\bin\\pushpoxy-0.0.1-SNAPSHOT.jar";
System.out.println("File has " + new File(filepath).length()+ " bytes");
FileInputStream fis = null;
fis = new FileInputStream(filepath);
System.out.println("File has " + fis.available() + " bytes");
}
运行结果 :
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.
我们把上面的程序稍微修改一下:
@Test
public void test01() throws IOException {
String filepath = "d:\\bin\\pushpoxy-0.0.1-SNAPSHOT.jar";
System.out.println("File has " + new File(filepath).length()+ " bytes");
FileInputStream fis = null;
fis = new FileInputStream(filepath);
byte[]bytes=new byte[10];
fis.read(bytes);
System.out.println("File has " + fis.available() + " bytes");
fis.skip(-10);
System.out.println("File has " + fis.available() + " bytes");
}
执行结果如下:
File has 29061936 bytes
File has 29061926 bytes
File has 29061936 bytes
总结:获取文件大小时建议使用File 的length()方法
推荐阅读
-
Spring MVC入门_动力节点Java学院整理
-
命令行可以执行java命令,脚本无效的解决办法;bash: java: command not found解决
-
java 获取文件大小
-
java.util.Formatter$FormatToken.unknownFormatConversionException(Formatter.java:1399) 的解决办法
-
java对同一个文件进行读写操作方法
-
java正则表达式表单验证类工具类(验证邮箱、手机号码、qq号码等)
-
Java设置Access-Control-Allow-Origin允许多域名访问的实现方法
-
Spring MVC全局异常处理和单元测试_动力节点Java学院整理
-
Java微信二次开发(二) Java微信文本消息接口请求与发送
-
Java中List Set和Map之间的区别_动力节点Java学院整理