2016-03-05 29 views
0

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

在Google上找到正确的短语令人惊讶地很难,这就是我来到这里的原因。

谢谢。

+0

你想要一个'InputStream',其行为这种方式,因为你想要的'next()的调用'“重返”的数据正在等待,还是我误解的东西的代码? –

+0

你是完全正确的,我是有错在我的头上。编辑问题。 – eyal3400

回答

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); 
      } 
     } 
    } 
} 
+0

这就是我需要的,谢谢。 – eyal3400

1

有JDK中没有这样的工具,但你完全可以包装你InputStreamDataInputStream并在其上调用readFully(byte[])

InputStream is = // ... 
DataInputStream dis = new DataInputStream(is); 
byte[] bytes = new byte[50]; 
dis.readFully(bytes); 
// "bytes" now contains exactly 50 bytes from the stream 

要与一个next()方法的类中,实现Iterator界面并在内部完成上述操作。

相关问题