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);
}
Was it helpful?

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top