当文件大小大于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);
}发布于 2013-06-01 11:36:56
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-01 11:34:33
正如感知力所说,你需要检查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);
}如FileInputStream的skip部分所述
由于各种原因,
方法可能会跳过一些较小的字节数,可能是0
https://stackoverflow.com/questions/16868748
复制相似问题