2

如果文件大小 > 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);
    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);
}
4

2 回答 2

2

InputStream API 说,由于各种原因,skip 方法最终可能会跳过一些较小的字节数。尝试这个

...
long n = in.skip(GAP_SIZE);
System.out.println(n);
...

它打印 8191 而不是预期的 8192。这与 BufferedInputStream 实现细节有关,如果你删除它(在这种具体情况下它不会提高性能)你会得到预期的结果

...
InputStream in = new FileInputStream(tmp);
...

输出

1
2
于 2013-06-01T03:36:55.937 回答
1

正如 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);
}

skip部分所述FileInputStream

由于各种原因,skip 方法最终可能会跳过一些较小的字节数,可能是 0

于 2013-06-01T03:34:33.097 回答