O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Skipping Bytes

Although you can just read from a stream and ignore the bytes read, Java provides a skip() method that jumps over a certain number of bytes in the input:

public long skip(long bytesToSkip) throws IOException

The argument to skip() is the number of bytes to skip. The return value is the number of bytes actually skipped, which may be less than bytesToSkip. -1 is returned if the end of stream is encountered. Both the argument and return value are longs, allowing skip() to handle extremely long input streams. Skipping is often faster than reading and discarding the data you don’t want. For example, when an input stream is attached to a file, skipping bytes just requires that an integer called the file pointer be changed, whereas reading involves copying bytes from the disk into memory. For example, to skip the next 80 bytes of the input stream in:

try {
  long bytesSkipped = 0;
  long bytesToSkip = 80;
  while (bytesSkipped < bytesToSkip) {
    long n = in.skip(bytesToSkip - bytesSkipped);
    if (n == -1) break;
    bytesSkipped += n;
  }
}
catch (IOException e) {System.err.println(e);}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required