Java BufferedInputStream行为
如果文件大小>8k,为什么最后一个字节读取=0Java BufferedInputStream行为,java,inputstream,behavior,bufferedinputstream,Java,Inputstream,Behavior,Bufferedinputstream,如果文件大小>8k,为什么最后一个字节读取=0 private static final int GAP_SIZE = 8 * 1024; public static void main(String[] args) throws Exception{ File tmp = File.createTempFile("gap", ".txt"); FileOutputStream out = new FileOutputStream(tmp); out.write(1);
private static final int GAP_SIZE = 8 * 1024;
public static void main(String[] args) throws Exception{
File tmp = File.createTempFile("gap", ".txt");
FileOutputStream out = new FileOutputStream(tmp);
out.write(1);
out.write(new byte[GAP_SIZE]);
out.write(2);
out.close();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmp));
int first = in.read();
in.skip(GAP_SIZE);
int last = in.read();
System.out.println(first);
System.out.println(last);
}
正如Perception所说,您需要检查
skip
的返回。如果我添加了一个检查和补偿,它将修复问题:
long skipped = in.skip(GAP_SIZE);
System.out.println( "GAP: " + GAP_SIZE + " skipped: " + skipped ) ;
if( skipped < GAP_SIZE)
{
skipped = in.skip(GAP_SIZE-skipped);
}
long skipped=in.skip(间隙大小);
System.out.println(“间隙:+间隙大小+”跳过:+跳过);
如果(跳过<间隙大小)
{
跳过=英寸跳过(间隙大小跳过);
}
如文件输入流
一节所述:
由于各种原因,skip方法可能会跳过一些较小的字节数,可能是0
InputStream API表示,由于各种原因,skip方法可能会跳过一些较小的字节数。试试这个
...
long n = in.skip(GAP_SIZE);
System.out.println(n);
...
它打印8191而不是预期的8192。这与BufferedInputStream实现细节有关,如果删除它(在这个具体的例子中,它不会提高性能),您将获得预期的结果
...
InputStream in = new FileInputStream(tmp);
...
输出
1
2
不保证跳过的实际字节数。你必须检查一下。似乎它不想跳过本机文件系统块大小。我很困惑。。。如果原因是FileInputStream中的skip方法,为什么删除BufferedInputStream可以解决问题?实际原因是BufferedInputStream实现详细信息,FileInputStream很好,您是对的,但我仍然感到困惑,正如FileInputStream skip所说:“由于各种原因,skip方法可能会跳过一些较小的字节数”。对,在real app中,我们应该在循环中使用skip,直到跳过所需的数字。我找到了原因:BufferedInputStream的defaultBufferSize=8192