有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java这个LimitedInputStream正确吗?

我编写了一个名为LimitedInputStream的类。它环绕现有的输入流,将从中读取的字节数限制为指定的长度。它的意思是作为一种替代:

byte[] data = readAll(length);
InputStream ins = new ByteArrayInputStream(data);

这需要额外的缓冲区

这是一节课:

public static class LimitedInputStream extends InputStream {
    private final InputStream ins;
    private int left;
    private int mark = -1;

    public LimitedInputStream(InputStream ins, int limit) {
        this.ins = ins;
        left = limit;
    }

    public void skipRest() throws IOException {
        ByteStreams.skipFully(ins, left);
        left = 0;
    }

    @Override
    public int read() throws IOException {
        if (left == 0) return -1;
        final int read = ins.read();
        if (read > 0) left--;
        return read;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (left == 0) return -1;
        if (len > left) len = left;
        final int read = ins.read(b, off, len);
        if (read > 0) left -= read;
        return read;
    }

    @Override
    public int available() throws IOException {
        final int a = ins.available();
        return a > left ? left : a;
    }

    @Override
    public void mark(int readlimit) {
        ins.mark(readlimit);
        mark = left;
    }

    @Override
    public void reset() throws IOException {
        if (!ins.markSupported()) throw new IOException("Mark not supported");
        if (mark == -1) throw new IOException("Mark not set");

        ins.reset();
        left = mark;
    }

    @Override
    public long skip(long n) throws IOException {
        if (n > left) n = left;
        long skipped = ins.skip(n);
        left -= skipped;
        return skipped;
    }

}

用例:

Object readObj() throws IOException {
    int len = readInt();
    final LimitedInputStream lis = new LimitedInputStream(this, len);
    try {
        return deserialize(new CompactInputStream(lis));
    } finally {
        lis.skipRest();
    }
}

for (something) {
  Object obj;
 try {
   obj = readObj();
 } catch (Exception e) {
   obj = null;
 }
 list.add(obj);
}

你能检查一下我的类有没有严重的错误,例如更新left时可能出现的错误吗


共 (1) 个答案

  1. # 1 楼答案

    番石榴包括一个LimitInputStream,所以你可能只想用它