Java Streams  «Prev  Next»

Lesson 5Skipping bytes
Objective Learn how to skip unnecessary data.

Skipping bytes in the input Stream

Although you could 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.
This can be quicker in some circumstances.
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.

Skip bytes in Java Streams Example:

To skip the next 80 bytes of the input stream is, you could write the following code:

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

Skipping Bytes in an Input Stream

The DataInputStream class's skipBytes() method skips over a specified number of bytes without reading them. Unlike the skip() method of java.io.InputStream that DataInputStream inherits, skipBytes() either skips over all the bytes it's asked to skip or it throws an exception:

public final int skipBytes(int n) throws IOException
public long skip(long n) throws IOException

skipBytes() blocks and waits for more data until n bytes have been skipped (successful execution) or an exception is thrown. The method returns the number of bytes skipped, which is always n (because if it's not n , an exception is thrown and nothing is returned). On end of stream, an EOFException is thrown. An IOException is thrown if the underlying stream throws an IOException.