背景介绍

在使用Java进行流操作的过程中,会出现需要重复使用流的情况,但是InputStream接口并未实现cloneable接口,因此不能实现复制,这是就要用到把流转换为另外一种形式,然后存入内存之中,并再次转化为流。

实现代码

public class CopyStream {

    public static void main(String[] args) throws IOException {

        File file = new File("‪E:\\03PCQQ文件\\Web应用安全规范 (2).doc");

        InputStream input = new FileInputStream(file);

        ByteArrayOutputStream baos = copyInputStream(input);

        // 复制出两个新的输入流(此时有一个InputStream的到两个相同的inputStream,如果需要多个还可以继续复制)
        InputStream codeStream = new ByteArrayInputStream(baos.toByteArray());

        InputStream opStream = new ByteArrayInputStream(baos.toByteArray());
    }

    /** * 流复制 */
    private static ByteArrayOutputStream copyInputStream(InputStream input) {

        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            // 定义一个缓存数组,临时存放读取的数组
            //经过测试,4*1024是一个非常不错的数字,过大过小都会比较影响性能
            byte[] buffer = new byte[4096];
            int length;
            while ((length= input.read(buffer)) > -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            throw new IOException(e);
        }
    }

}



以上即实现了流的复制。