在日常的编码中,有时会遇到,需要重复获取InputStream中的数据的需求;然后一般的流,只能读一次,读完就没了;那么如果我希望有一个可以重复读取数据的InputStream,可以怎么操作?
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | 
 
 
 
 
 
 public static ByteArrayInputStream toByteArrayInputStream(InputStream inputStream) throws IOException {
 if (inputStream instanceof ByteArrayInputStream) {
 return (ByteArrayInputStream) inputStream;
 }
 
 try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
 BufferedInputStream br = new BufferedInputStream(inputStream);
 byte[] b = new byte[1024];
 for (int c; (c = br.read(b)) != -1; ) {
 bos.write(b, 0, c);
 }
 
 b = null;
 br.close();
 inputStream.close();
 return new ByteArrayInputStream(bos.toByteArray());
 }
 }
 
 | 
实现方式基本就是将InputStream中的数据读取,写入到一个临时的输出流,然后再封装为ByteArrayInputStream即可
当我们使用时,如果需要重复消费流中数据,手动调用java.io.ByteArrayInputStream#reset
II. 其他
一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
2. 声明
尽信书则不如,已上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激
3. 扫描关注
一灰灰blog

知识星球
