Course contentsShow
← Java
Lesson 1910 of 2,87039. File I/O: Basic Byte StreamsFree lesson

The skip(long) Method for Skipping Bytes

Efficiently skipping over bytes in an input stream without reading them into memory.

The skip(long) Method for Skipping Bytes

You'll learn how to efficiently jump over unwanted bytes in an input stream without wasting memory by reading them.

What Is skip(long)?

When reading from an InputStream, you sometimes need to bypass a portion of data—like skipping a file header or jumping to a specific position. The skip(long n) method lets you move forward in the stream by discarding up to n bytes without loading them into memory. This is much faster and more efficient than reading those bytes into an array just to throw them away.

How It Works

Think of an input stream like a tape player. If you want to skip the first 30 seconds of a song, you fast-forward without listening to that part. Similarly, skip() advances the stream's position without processing the bytes in between.

InputStream input = // some stream source
long bytesSkipped = input.skip(1024); // Try to skip 1024 bytes

The method returns the actual number of bytes skipped, which may be less than requested if the stream ends sooner or if skipping isn't fully supported.

Key Behaviors

  • Return value matters: Always check how many bytes were actually skipped—it might be fewer than you requested
  • Not guaranteed: The method makes a "best effort" but may skip zero bytes in some cases
  • Stream position advances: After skipping, the next read() starts from the new position
  • No memory allocation: Unlike reading into a byte array, skipping doesn't require buffer space

Why Use It?

Use skip() when you need to ignore data efficiently: bypassing fixed-size headers, jumping to record boundaries, or repositioning within structured binary files.

Key Takeaway: The skip(long) method efficiently advances an input stream's position without reading bytes into memory, returning the actual number of bytes skipped (which may be less than requested).