Question

I wanted to use the skip method of FilterInputStream class which should skip over the required number of bytes from the stream. But the documentation for the skip method says http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FilterInputStream.html#skip(long)

Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. The actual number of bytes skipped is returned.

Is it really safe to use then the skip method for the purpose of seeking to a particular position?

Was it helpful?

Solution

I also find this API a little problematic. It leaves too much freedom to the specific implementations:

1) It's not clear what happens in case of end of stream

2) It's not clear whether when the stream is non-empty, repeatedly calling skip will eventually return a positive number or not.

Assuming that you know that n isn't beyond the end of stream, and assuming that (2) holds, then the following code may be helpful:

public static void skipSecure(InputStream is, long n) throws IOException {
    while (n >= 0) {
        long skipped = is.skip(n);
        n -= skipped;
    }
}

OTHER TIPS

FilterInputStream is just a wrapper for an underlying InputStream, so it depends on the underlying InputStream.skip behaviour.

For example, if the underlying InputStream is FileInputStream, then we should refer to the FileInputStream#skip API which states:

public long skip(long n) throws IOException

Skips over and discards n bytes of data from the input stream.

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. If n is negative, an IOException is thrown, even though the skip method of the InputStream superclass does nothing in this case. The actual number of bytes skipped is returned.

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.

From this description FileInputStream.skip does not seem reliable to me.

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