通过计数和File.length()

时间:2015-10-02 13:30:57

标签: java file

我正在将File.length()与计数字节进行比较,我总是使用File.length()得到1个字节。

以下是我用来比较的片段:

File testFile = new File("testdir", "testfile.txt");
FileInputStream in = new FileInputStream(testFile );

byte[] buffer = new byte[1024];
int len = in.read(buffer);

int byteCount = len;
while (len != -1) {
    len = in.read(buffer);
    byteCount += len;
}
System.out.println("count: " + byteCount + ", file.length(): " + 
     testFile.length() + ", is_equal: "+(byteCount == testFile.length()));

,输出为count: 15853294, file.length(): 15853295, is_equal: false

1个字节来自哪里?是EOF?

1 个答案:

答案 0 :(得分:10)

最后一次read操作返回-1,您将其添加到byteCount