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时退出循环,而不是像你这样晚很多。