Java 按计数和file.length()计算的文件大小相差1字节

Java 按计数和file.length()计算的文件大小相差1字节,java,file,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

我将
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吗

最后一次
read
操作返回-1,您将其添加到
byteCount
最后一次
read
操作返回-1,您将其添加到
byteCount
,而不是
while(len!=-1){
我通常写入
while((len=inp.read(buffer))!=-1){
,它在读取返回-1时退出循环,而不是像你这样晚很多。我通常写
而不是((len=inp.read(buffer))!=-1),它在读取返回-1时退出循环,而不是像你这样晚很多。