序列流可以把多个字节输入流整合成一个, 从序列流中读取数据时, 将从被整合的第一个流开始读, 读完一个之后继续读第二个, 以此类推.

将2个文件中的数据输出到1个文件中

  1. abcdefg
  1. 1234567890
  1. @Test
  2. public void demo1() throws IOException {
  3. FileInputStream fis1 = new FileInputStream("other\\input1.txt"); //创建字节输入流关联a.txt
  4. FileOutputStream fos = new FileOutputStream("other\\output.txt"); //创建字节输出流关联c.txt
  5. int b1;
  6. while((b1 = fis1.read()) != -1) { //不断的在a.txt上读取字节
  7. fos.write(b1); //将读到的字节写到c.txt上
  8. }
  9. fis1.close(); //关闭字节输入流
  10. FileInputStream fis2 = new FileInputStream("other\\input2.txt");
  11. int b2;
  12. while((b2 = fis2.read()) != -1) {
  13. fos.write(b2);
  14. }
  15. fis2.close();
  16. fos.close();
  17. }

输出后的文件

abcdefg1234567890

使用序列流整合2个输入流

    /**
     * 使用序列流SequenceInputStream,读取2个字节流,输出到1个字节流中
     * @throws IOException
     */
    @Test
    public void demo2() throws IOException {
        FileInputStream fis1 = new FileInputStream("other\\input1.txt");
        FileInputStream fis2 = new FileInputStream("other\\input2.txt");
        /**
         * 整合两个输入流
         * SequenceInputStream(InputStream s1, InputStream s2)
         */
        SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
        FileOutputStream fos = new FileOutputStream("other\\output2.txt");

        int b;
        while((b = sis.read()) != -1) {
            fos.write(b);
        }

        sis.close();                    //sis在关闭的时候,会将构造方法中传入的流对象也都关闭
        fos.close();
    }
abcdefg1234567890

使用序列流整合多个输入流

引入第3个文件

!@#$%^&*()
@Test
public void demo3() throws IOException {

    FileInputStream fis1 = new FileInputStream("other\\input1.txt");
    FileInputStream fis2 = new FileInputStream("other\\input2.txt");
    FileInputStream fis3 = new FileInputStream("other\\input3.txt");

    Vector<FileInputStream> v = new Vector<>();                    //创建集合对象
    v.add(fis1);                                                //将流对象存储进来
    v.add(fis2);
    v.add(fis3);

    Enumeration<FileInputStream> en = v.elements();
    SequenceInputStream sis = new SequenceInputStream(en);        //将枚举中的输入流整合成一个
    FileOutputStream fos = new FileOutputStream("other\\output3.txt");

    int b;
    while((b = sis.read()) != -1) {
        fos.write(b);
    }

    sis.close();
    fos.close();
    }
abcdefg1234567890!@#$%^&*()