1

I'm running the following code:

public class SkipTest {
    public static void main(String[] args) throws IOException {
        FileOutputStream fileout = new FileOutputStream("./foo");
        DataOutputStream output = new DataOutputStream( fileout );
        output.writeLong(12345678L);
        output.writeLong(87654321L);
        output.writeInt(1234);
        output.flush();
        output.close();

        FileInputStream input = new FileInputStream("./foo");
        DataInputStream datain = new DataInputStream(input);

        System.out.println(datain.readLong());
        System.out.println(datain.readLong());

        long skipped = datain.skip(8);
        System.out.printf("Attempting to skip 8 bytes, actually skipped %d.\n", skipped);

        datain.close();
    }
}

According to the docs, the return value of .skip() is the actual number of bytes skipped, which may be less than the requested number. I've verified that the file is only 20 bytes externally, but when I run the code above I get the following output:

12345678
87654321
Attempting to skip 8 bytes, actually skipped 8.

So is this a bug or am I doing something wrong? How can it skip 8 bytes when there are only 4 left in the file?

job
  • 9,003
  • 7
  • 41
  • 50

2 Answers2

4

The DataInputStream is passing down through FileInputStream which claims the following for its implementation of skip:

"This method may skip more bytes than are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file."

Sticks
  • 402
  • 3
  • 9
  • Thanks, I was only looking at the docs for InputStream and I didn't think to check FileInputStream. I still think it's misleading that it says the return value is "the actual number of bytes skipped". – job Jul 16 '12 at 21:32
1

You can skip an arbitrary number of bytes in a FileInputStream, apparently without reading anything. It will just reposition the cursor and the next read will then fail. Try datain.skip(Integer.MAX_VALUE).

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436