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);}Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access