< prev index next >
src/java.base/share/classes/java/io/InputStream.java
Print this page
@@ -62,12 +62,12 @@
* effect.
*
* <p> While the stream is open, the {@code available()}, {@code read()},
* {@code read(byte[])}, {@code read(byte[], int, int)},
* {@code readAllBytes()}, {@code readNBytes(byte[], int, int)},
- * {@code readNBytes(int)}, {@code skip(long)}, and
- * {@code transferTo()} methods all behave as if end of stream has been
+ * {@code readNBytes(int)}, {@code skip(long)}, {@code skipNBytes(long)},
+ * and {@code transferTo()} methods all behave as if end of stream has been
* reached. After the stream has been closed, these methods all throw
* {@code IOException}.
*
* <p> The {@code markSupported()} method returns {@code false}. The
* {@code mark()} method does nothing, and the {@code reset()} method
@@ -137,10 +137,18 @@
ensureOpen();
return 0L;
}
@Override
+ public void skipNBytes(long n) throws IOException {
+ ensureOpen();
+ if (n > 0) {
+ throw new EOFException();
+ }
+ }
+
+ @Override
public long transferTo(OutputStream out) throws IOException {
Objects.requireNonNull(out);
ensureOpen();
return 0L;
}
@@ -511,15 +519,14 @@
* have been read or the end of the stream has been reached. Subclasses are
* encouraged to provide a more efficient implementation of this method.
* For instance, the implementation may depend on the ability to seek.
*
* @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
+ * @return the actual number of bytes skipped which might be zero.
* @throws IOException if an I/O error occurs.
*/
public long skip(long n) throws IOException {
-
long remaining = n;
int nr;
if (n <= 0) {
return 0;
@@ -537,10 +544,30 @@
return n - remaining;
}
/**
+ * Skips over and discards exactly {@code n} bytes of data from this input
+ * stream. If {@code n <= 0}, no bytes are skipped. If {@code n > 0},
+ * then {@code n} bytes of data are skipped unless end of stream is
+ * encountered first, in which case an {@code EOFException} is thrown.
+ *
+ * <p> This method blocks until data is available to skip, end of file is
+ * detected, or an exception is thrown.
+ *
+ * @param n the number of bytes to be skipped.
+ * @throws EOFException if end of stream is encountered before {@code n}
+ * bytes are skipped.
+ * @throws IOException if an I/O error occurs.
+ */
+ public void skipNBytes(long n) throws IOException {
+ if (n > 0 && skip(n) != n) {
+ throw new EOFException("End of stream before enough bytes skipped");
+ }
+ }
+
+ /**
* Returns an estimate of the number of bytes that can be read (or skipped
* over) from this input stream without blocking, which may be 0, or 0 when
* end of stream is detected. The read might be on the same thread or
* another thread. A single read or skip of this many bytes will not block,
* but may read or skip fewer bytes.
< prev index next >