不支持标记时如何正确实现 InputStream.mark()
How to correctly implement InputStream.mark() when mark is not supported
这是一个关于正确实现 Java 的 InputStream
接口的问题。
我有一个 不支持 mark/reset 功能的实现。因此 markSupported
方法中的 returns false。在这种情况下,我应该如何实现 mark
方法?也就是说,如果有人在被告知不支持标记的情况下仍调用 mark
,应该如何处理?
两个明显的选择是:(a) 忽略它,什么都不做;或 (b) 抛出 UnsupportedOperationException
。 API Java文档不提供任何关于首选的指导。
我建议像 class InputStream
那样做,即
mark()
:按照 javadoc "The mark method of InputStream does nothing." 中所述不执行任何操作
reset()
:抛出一个 I/O 异常,如 javadoc "The method reset for class InputStream does nothing except throw an IOException." 中所述
Javadoc link : https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
看起来 JDK 中的典型实现什么都不做,如果调用 reset
则抛出 IOException:
java.util.zip.InflaterInputStream:
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
java.io.PushbackInputStream:
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
这是一个关于正确实现 Java 的 InputStream
接口的问题。
我有一个 不支持 mark/reset 功能的实现。因此 markSupported
方法中的 returns false。在这种情况下,我应该如何实现 mark
方法?也就是说,如果有人在被告知不支持标记的情况下仍调用 mark
,应该如何处理?
两个明显的选择是:(a) 忽略它,什么都不做;或 (b) 抛出 UnsupportedOperationException
。 API Java文档不提供任何关于首选的指导。
我建议像 class InputStream
那样做,即
mark()
:按照 javadoc "The mark method of InputStream does nothing." 中所述不执行任何操作
reset()
:抛出一个 I/O 异常,如 javadoc "The method reset for class InputStream does nothing except throw an IOException." 中所述
Javadoc link : https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
看起来 JDK 中的典型实现什么都不做,如果调用 reset
则抛出 IOException:
java.util.zip.InflaterInputStream:
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
java.io.PushbackInputStream:
public synchronized void mark(int readlimit) {
}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}