好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现InputStream的任意拷贝方式

Java InputStream的任意拷贝

有时候,当我们需要多次使用到同一个InputStream的时候如何实现InputStream的拷贝使用

我们可以把InputStream首先转换成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()的方法进行相关的操作

复制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 ;

     }

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/jys1115/article/details/42642549

查看更多关于Java实现InputStream的任意拷贝方式的详细内容...

  阅读:39次