天天看點

InputStream隻能讀取一次的解決方法

有時候我們需要對同一個InputStream對象使用多次。

但第一次讀取InputStream對象後,第二次再讀取時可能已經到Stream的結尾了(EOFException)或者Stream已經close掉了。

而InputStream對象本身不能複制,因為它沒有實作Cloneable接口。此時,可以先把InputStream轉化成ByteArrayOutputStream,後面要使用InputStream對象時,再從ByteArrayOutputStream轉化回來就好了。代碼實作如下:

// 從request中擷取流,取出來的流隻能使用一次
InputStream inputStream = request.getInputStream();

ByteArrayOutputStream baosOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte];
int len;
while ((len = inputStream.read(buffer)) >) {
    baosOutputStream.write(buffer,, len);
}
baosOutputStream.flush();

InputStream stream1 = new ByteArrayInputStream(baosOutputStream.toByteArray());
InputStream stream2 = new ByteArrayInputStream(baosOutputStream.toByteArray());

//一定要記得關閉資源,先開後關
stream2.close();
stream2 = null;
stream1.close();
stream1 = null;
baosOutputStream.close();
baosOutputStream = null;
inputStream.close();
inputStream = null;