Question

Why is the LAST Byte read = 0 if the file size > 8k?

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);
}
Était-ce utile?

La solution

InputStream API says that the skip method may, for a variety of reasons, end up skipping over some smaller number of bytes. Try this

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

it prints 8191 instead of expected 8192. This is related to BufferedInputStream implementation details, if you remove it (it doesn't improove performance in this concrete case anyway) you will get the expected result

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

output

1
2

Autres conseils

As Perception said, you need to check the return of skip. If I add a check and compensate it fixes the problem:

long skipped = in.skip(GAP_SIZE);
System.out.println( "GAP: " + GAP_SIZE + " skipped: " + skipped ) ;
if( skipped < GAP_SIZE)
{
   skipped = in.skip(GAP_SIZE-skipped);
}

As stated in the skip section for FileInputStream:

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top