Java实现InputStream的任意拷贝方式
作者:曲终人散J 时间:2022-04-08 10:11:32
Java InputStream的任意拷贝
有时候,当我们需要多次使用到同一个InputStream的时候如何实现InputStream的拷贝使用
我们可以把InputStream首先转换成ByteArrayOutputStream.然后你就可以任意克隆你需要的InputStream了
代码如下:
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流的代码
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,任意拷贝
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mybatis 报错显示sql中有两个limit的解决
2022-04-30 02:50:49
![](https://img.aspxhome.com/file/2023/4/84784_0s.png)
SpringCloud Edgware.SR3版本中Ribbon的timeout设置方法
2023-03-07 10:45:46
JAVA 生成随机数并根据后台概率灵活生成的实例代码
2023-12-05 11:00:48
Spring Security过滤器链体系的实例详解
2023-08-25 03:24:15
![](https://img.aspxhome.com/file/2023/8/58208_0s.png)
BeanDefinition基础信息讲解
2022-03-23 23:48:37
IDEA 2020.1 版自动导入MAVEN依赖的方法(新版MAVEN无法自动导入/更新POM依赖、MAVEN设置自动更新、自动更新快捷键)
2022-08-27 09:31:22
![](https://img.aspxhome.com/file/2023/4/88504_0s.png)
面试官:详细谈谈Java对象的4种引用方式
2022-09-19 04:52:20
基于Spring Security前后端分离的权限控制系统问题
2022-10-16 21:32:39
![](https://img.aspxhome.com/file/2023/4/66254_0s.png)
分析SpringBoot的启动原理
2021-10-30 16:01:23
![](https://img.aspxhome.com/file/2023/4/69324_0s.png)
Java中遍历ConcurrentHashMap的四种方式详解
2023-11-17 08:54:41
Seata AT模式TM处理流程图文示例详解
2022-05-03 02:28:39
![](https://img.aspxhome.com/file/2023/4/71864_0s.png)
SpringBoot整合Shiro实现登录认证的方法
2022-03-23 01:12:19
![](https://img.aspxhome.com/file/2023/5/64755_0s.png)
springboot FeignClient注解及参数
2021-07-09 21:59:07
解决微服务feign调用添加token的问题
2023-09-11 09:38:05
![](https://img.aspxhome.com/file/2023/1/58331_0s.jpg)
prometheus监控springboot应用简单使用介绍详解
2023-02-24 03:49:00
Java TreeSet实现学生按年龄大小和姓名排序的方法示例
2023-01-09 15:25:18
Java由浅入深刨析继承
2023-11-23 08:04:24
![](https://img.aspxhome.com/file/2023/4/59564_0s.jpg)
Java获取用户IP属地模拟抖音详解
2023-04-18 02:01:29
![](https://img.aspxhome.com/file/2023/7/81897_0s.jpg)
Java基本数据类型与类型转换实例分析
2021-07-13 14:41:29
![](https://img.aspxhome.com/file/2023/8/71018_0s.png)
Android 之Preference控件基本使用示例详解
2022-10-20 23:42:34
![](https://img.aspxhome.com/file/2023/9/86019_0s.jpg)