Java_基础—序列流整合多个

来源:互联网 发布:制作假证件软件 编辑:程序博客网 时间:2024/05/21 15:58
package com.soar.otherio;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.Enumeration;import java.util.Vector;public class Demo1_SequenceInputStream {    /** * * 1.什么是序列流     * 序列流可以把多个字节输入流整合成一个, 从序列流中读取数据时, 将从被整合的第一个流开始读, 读完一个之后继续读第二个, 以此类推.* * * 2.使用方式     * 整合两个: SequenceInputStream(InputStream, InputStream)     * 整合多个: SequenceInputStream(Enumeration)     */    public static void main(String[] args) throws IOException {        //demo1();        //demo2();        FileInputStream fis1 = new FileInputStream("a.txt");        FileInputStream fis2 = new FileInputStream("b.txt");        FileInputStream fis3 = new FileInputStream("c.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("d.txt");        int b;        while((b = sis.read()) != -1){            fos.write(b);        }        sis.close();        fos.close();    }    private static void demo2() throws FileNotFoundException, IOException {        FileInputStream fis1 = new FileInputStream("a.txt");        FileInputStream fis2 = new FileInputStream("b.txt");        SequenceInputStream sis = new SequenceInputStream(fis1, fis2);        FileOutputStream fos = new FileOutputStream("c.txt");        int b;        while((b = sis.read()) != -1){            fos.write(b);        }        sis.close();            //sis在关闭的时候,会将构造方法中传入的流对象也都关闭        fos.close();    }    private static void demo1() throws FileNotFoundException, IOException {        FileInputStream fis1 = new FileInputStream("a.txt");    //创建字节输入流关联a.txt        FileOutputStream fos = new FileOutputStream("c.txt");   //创建字节输出流关联c.txt        int b1;        while((b1 = fis1.read()) != -1){        //不断地在a.txt上读取字节            fos.write(b1);                      //将独到的字节写道c.txt        }        fis1.close();                           //关闭字节流        FileInputStream fis2 = new FileInputStream("b.txt");        int b2;        while((b2 = fis2.read()) != -1){            fos.write(b2);        }        fis2.close();        fos.close();    }}
原创粉丝点击