Java IO流-合并流

2017-11-05 20:15:28

  • SequenceinputStream

SequenceinputStream:SequenceInputStream 表示其他输入流的逻辑串联。它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。

*构造方法

*常用方法

public class Demo6 {

    public static void main(String[] args) throws IOException {
        InputStream in1 = new FileInputStream("E:/text.txt");
        InputStream in2 = new FileInputStream("E:/text2.txt");

        SequenceInputStream sis = new SequenceInputStream(in1, in2);
        BufferedOutputStream bs = new BufferedOutputStream(new FileOutputStream("" +
                "E:/copy.txt"));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = sis.read(bys)) != -1) {
            bs.write(bys, 0, len);
        }

        bs.close();
        sis.close();
    }

}

如果超过两个该怎么办呢?其实该类还提供了另一个构造方法:public SequenceInputStream(Enumeration<? extends InputStream> e)

这里的Enumeration枚举器是Vector类的一个方法的返回值:public Enumeration<E> elements()

剩下的就非常简单了:

public class Demo6 {

    public static void main(String[] args) throws IOException {
        Vector<InputStream> v = new Vector<>();
        InputStream in1 = new FileInputStream("E:/text.txt");
        InputStream in2 = new FileInputStream("E:/text2.txt");
        InputStream in3 = new FileInputStream("E:/text3.txt");
        
        v.add(in1);
        v.add(in2);
        v.add(in3);

        Enumeration<InputStream> enumeration = v.elements();

        SequenceInputStream sis = new SequenceInputStream(enumeration);
        BufferedOutputStream bs = new BufferedOutputStream(new FileOutputStream("" +
                "E:/copy.txt"));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = sis.read(bys)) != -1) {
            bs.write(bys, 0, len);
        }

        bs.close();
        sis.close();
    }

}

 

posted @ 2017-11-05 20:42  hyserendipity  阅读(1374)  评论(0编辑  收藏  举报