Java InputStream的任意拷貝
有時候,當(dāng)我們需要多次使用到同一個InputStream的時候如何實現(xiàn)InputStream的拷貝使用
我們可以把InputStream首先轉(zhuǎn)換成ByteArrayOutputStream.然后你就可以任意克隆你需要的InputStream了
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte [] buffer = new byte [ 1024 ]; int len; while ((len = input.read(buffer)) > - 1 ) { baos.write(buffer, 0 , len); } baos.flush(); // 打開一個新的輸入流 InputStream is1 = new ByteArrayInputStream(baos.toByteArray()); InputStream is2 = new ByteArrayInputStream(baos.toByteArray()); |
但是如果你真的需要保持一個原始的輸入流去接收信息,你就需要捕獲輸入流的close()的方法進(jìn)行相關(guān)的操作
復(fù)制InputStream流的代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private static InputStream cloneInputStream(InputStream input) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte [] buffer = new byte [ 1024 ]; int len; while ((len = input.read(buffer)) > - 1 ) { baos.write(buffer, 0 , len); } baos.flush(); return new ByteArrayInputStream(baos.toByteArray()); } catch (IOException e) { e.printStackTrace(); return null ; } } |
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/jys1115/article/details/42642549