java 中计算文件长度:FileReader 与 File.length
为什么下面代码中的 fr_count 和 len 会不同?
FileReader fr = new FileReader(filename);
int c;
long fr_count = 0;
while ( -1 != (c = fr.read()) )
fr_count++;
long len = new File(filename).length();
我在两个文件上使用了上面的代码。结果如下:
test.txt
FileReader: 263742
File.length: 265963
output.enc
FileReader: 146360
File.length: 212998
Why would fr_count and len be different in the code below?
FileReader fr = new FileReader(filename);
int c;
long fr_count = 0;
while ( -1 != (c = fr.read()) )
fr_count++;
long len = new File(filename).length();
I've used the code above on two files. Here are the results:
test.txt
FileReader: 263742
File.length: 265963
output.enc
FileReader: 146360
File.length: 212998
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fr_count
是您从文件中读取的字符数。len
是文件中的字节数。它们是两个非常不同的东西。例如,某些字符以多个字节表示,某些编码使用字节顺序标记。这两者都会造成文件中字符数和字节数之间的差异。fr_count
is the number of characters you read from the file.len
is the number of bytes in the file. They're two very different things. E.g. some characters are represented in multiple bytes, and some encodings use a byte order mark. Both of these will make for differences between the number of characters and the number of bytes in a file.File.Length
返回文件中的字节
数。计算FileReader.read()
可以告诉您文件中有多少个字符。File.Length
is returning the number ofBytes
in the file. CountingFileReader.read()
is telling you how many characters are in the file.