我想创建一个仅限于文件中某个字节范围的InputStream,例如从0到100的字节.因此客户端代码应该在达到第100个字节时看到EOF.
dan*_*ben 10
一次读取一个字节的read()方法InputStream.你可以写一个InputStream维护内部计数器的子类; 每次read()调用,更新计数器.如果达到最大值,则不允许进一步读取(返回-1或类似的东西).
您还需要确保read_int不支持其他读取方法(例如:覆盖它们并抛出UnsupportedOperationException());
我不知道你的用例是什么,但作为奖励你也可能想要实现缓冲.
正如danben所说,只需装饰您的流并强制执行约束:
public class ConstrainedInputStream extends InputStream {
private final InputStream decorated;
private long length;
public ConstrainedInputStream(InputStream decorated, long length) {
this.decorated = decorated;
this.length = length;
}
@Override public int read() throws IOException {
return (length-- <= 0) ? -1 : decorated.read();
}
// TODO: override other methods if you feel it's necessary
// optionally, extend FilterInputStream instead
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7138 次 |
| 最近记录: |