开发者

counting file length in java: FileReader vs. File.length

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_cou开发者_Python百科nt++;
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


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 is returning the number of Bytes in the file. Counting FileReader.read() is telling you how many characters are in the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜