給定一個InputStream,我想要一個工具,我呼叫next()
,當前執行塊直到流中累積了50個字節,此時next()
返回一個長度爲50的byte[]
,包含相關數據。從每個固定字節長度的InputStream中繪製數據?
在Google上找到正確的短語令人驚訝地很難,這就是我來到這裏的原因。
謝謝。
給定一個InputStream,我想要一個工具,我呼叫next()
,當前執行塊直到流中累積了50個字節,此時next()
返回一個長度爲50的byte[]
,包含相關數據。從每個固定字節長度的InputStream中繪製數據?
在Google上找到正確的短語令人驚訝地很難,這就是我來到這裏的原因。
謝謝。
您一定應該參考標準的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);
}
}
}
}
這就是我需要的,謝謝。 – eyal3400
有JDK中沒有這樣的工具,但你完全可以包裝你InputStream
爲DataInputStream
並在其上調用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
界面並在內部完成上述操作。
你想要一個'InputStream',其行爲這種方式,因爲你想要的'next()的調用'「重返」的數據正在等待,還是我誤解的東西的代碼? –
你是完全正確的,我是有錯在我的頭上。編輯問題。 – eyal3400