Java FileChannel.size()与File.length() [英] Java FileChannel.size() vs File.length()

查看:517
本文介绍了Java FileChannel.size()与File.length()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何情况下 FileChannel.size() File.length()会有所不同吗?请参见下面的代码示例:

 文件file =新File(name); 
FileInputStream流=新的FileInputStream(文件);
FileChannel channel = stream.getChannel();
long channel_size = channel.size();
long file_length = file.length();


解决方案

它们可以有所不同,因为 new File(name).length()始终检查给定的路径。使用 FileInputStream 时,无论文件发生什么,都将附加到该文件。



例如,在Linux中您可以重命名,替换或删除正在使用的文件。 FileInputStream 将继续提供原始文件的大小,而 File 将为您提供替换后的文件,如果有的话。 / p>

Are there any circumstances where FileChannel.size() and File.length() will be different? Please see the code example below:

File file = new File(name);
FileInputStream stream = new FileInputStream(file);
FileChannel channel = stream.getChannel();
long channel_size = channel.size();
long file_length = file.length();

解决方案

They can be different because the new File(name).length() always checks the path given. When you use FileInputStream, you attach to that file regardless of what happens to it.

For example, in Linux you can rename, replace or delete a file which is in use. The FileInputStream will continue to give the original file's size whereas the File will give you what replaced it, if any.

这篇关于Java FileChannel.size()与File.length()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆