序列流(SequenceInputStream)

来源:互联网 发布:软件开发 私活 价格 编辑:程序博客网 时间:2024/05/21 09:16

 序列流: 也称为合并流。 SequenceInputStream ,对多个流进行合并。   

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

代码实例:

/*序列流:将多个流进行逻辑串联(合并成为一个流,使操作变得更加方便,因为多个源变成了一个源) *SequenceInputStream sis=new SequenceInputStream(InputStream s1, InputStream s2) ; *当要合并三个或三个以上的流时,需要使用枚举作为参数 *SequenceInputStream sis=new SequenceInputStream(Enumeration<? extends InputStream> e); */@Test//把三个文件中的数据写入到一个文件中public void sequenceInputStreamDemo() throws IOException{InputStream is1=new FileInputStream("1.txt");InputStream is2=new FileInputStream("2.txt");InputStream is3=new FileInputStream("3.txt");Collection<InputStream> col=new ArrayList<InputStream>();col.add(is1);col.add(is2);col.add(is3);//import java.util.Collections;这个包中有很多操作集合的方法Enumeration<InputStream> e = Collections.enumeration(col);//把is1,is2,is3三个流合并成为了一个流sisSequenceInputStream sis=new SequenceInputStream(e);OutputStream is=new FileOutputStream("seq.txt");int len=0;byte b[]=new byte[4];while((len=sis.read(b))!=-1){//先把合并流中的数据读取到字节数组b中is.write(b,0,len);  //在把字节数组中的数据写入到seq文件夹}}

1.txt

hello1
2.txt

hello2
3.txt

hello3

seq.txt

hello1hello2hello3