Java FileChannel.size() vs File.length()

我们两清 提交于 2019-12-13 21:13:49

问题


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();

回答1:


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.



来源:https://stackoverflow.com/questions/21293031/java-filechannel-size-vs-file-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!