每个固定字节长度从InputStream中提取数据?

时间:2016-03-05 17:20:58

标签: java inputstream

给定一个InputStream,我想要一个我调用next()的工具,当前执行块直到流中累积了50个字节,此时next()返回byte[]长度50,包含相关数据。

在Google上找到合适的短语非常困难,这就是我在这里的原因。

感谢。

2 个答案:

答案 0 :(得分:1)

JDK中没有这样的工具,但您只需将InputStream is = // ... DataInputStream dis = new DataInputStream(is); byte[] bytes = new byte[50]; dis.readFully(bytes); // "bytes" now contains exactly 50 bytes from the stream 打包到DataInputStream并在其上调用readFully(byte[])即可:

next()

要使用 pd.Series( [i for i in range(20)], pd.date_range('2016-01-02', periods=20, freq='D')) 方法创建一个类,请实现Iterator接口并在内部执行上述操作。

答案 1 :(得分:0)

您应该参考标准的JDK库,以获得优秀的类来读写IO。但你的要求相当有趣。你想要一个"迭代器"输入流的接口类型。所以,这是我的尝试。当然,一些优化是可能的,但希望它能很好地展现出这个想法。如果这是您正在寻找的,请告诉我。我承认合同有一个微妙的变化,因为方法hasNext()阻塞了基础输入流。我希望没关系。

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;

/** An attempt for:
 * http://stackoverflow.com/questions/35817251/draw-data-from-inputstream-every-fixed-byte-length
 *  <b>This class is NOT thread safe.</b>
 * Created by kmhaswade on 3/5/16.
 */
public class InputStreamIterator extends BufferedInputStream implements Iterator<byte[]> {

    private final InputStream in;
    private final byte[] bytes;
    private int bytesRead;
    /**
     * Returns a buffered input stream that "iterates" over a given stream. Follows the decorator pattern.
     * @param in the input stream that should be buffered
     * @param n
     */
    public InputStreamIterator(InputStream in, int n) {
        super(in);
        this.in = in;
        if (n <=0 || n > Integer.MAX_VALUE)
            throw new IllegalArgumentException("illegal value: " + n);
        bytes = new byte[n];
    }

    @Override
    public boolean hasNext() {
        try {
            bytesRead = super.read(this.bytes);
            if (bytesRead == -1) {
                this.close();
                return false;
            }
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e); // could be handled better ...
        }
    }

    @Override
    public byte[] next() {
        if (bytes.length == bytesRead)
            return bytes;
        else
            return Arrays.copyOf(bytes, bytesRead);
    }

    @Override
    public void remove() {
        throw new RuntimeException("no way to push back yet");
    }

    @Override
    public void forEachRemaining(Consumer<? super byte[]> action) {
        throw new RuntimeException("not yet implemented");
    }

    public static void main(String[] args) {
        InputStreamIterator itIn = new InputStreamIterator(System.in, 50);
        while (itIn.hasNext()) {
            byte[] bs = itIn.next();
            for (byte b : bs) {
                System.out.println("byte read: " + b);
            }
        }
    }
}