1、使用ByteArrayOutputStream和ByteArrayInputStream复制克隆(clone)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());
或者
ByteArrayOutputStream baos = new ByteArrayOutputStream(); input.transferTo(baos); InputStream firstClone = new ByteArrayInputStream(baos.toByteArray()); InputStream secondClone = new ByteArrayInputStream(baos.toByteArray());
相关文档:
2、使用apache.commons的IOUtils.toBufferedInputStream复制克隆(clone)InputStream
maven引用commons-io的pom.xml的配置:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
public void cloneStream() throws IOException{ InputStream toCopy=IOUtils.toInputStream("aaa"); InputStream dest= null; dest=IOUtils.toBufferedInputStream(toCopy); toCopy.close(); String result = new String(IOUtils.toByteArray(dest)); System.out.println(result); }
相关文档:
Java InputStream流转换读取成byte[]字节数组方法及示例代码