当前位置:首页 > 通信资讯 > 正文

javastream深拷贝(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

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。