Java---IO流之序列流(文件合并)

来源:互联网 发布:网络需求分析报告 编辑:程序博客网 时间:2024/06/03 18:26

★序列流
SequenceInputStream ——对多个流进行合并
将多个流进行逻辑串联(合并变成一个流,操作起来很方便,因为多个源变成了一个源)

这里写图片描述

package cn.hncu.io.sequence;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;//这个比较其他的演示知识点多了点---要求掌握!!!/* * ★序列流 SequenceInputStream  ——对多个流进行合并 将多个流进行逻辑串联(合并变成一个流,操作起来很方便,因为多个源变成了一个源)  */public class SequenceXxx {    public static void main(String[] args) {        //将多个流进行合并操作,且可以将多个文件中的数据读取到一个文件中去        FileOutputStream fout = null;        FileInputStream file1 = null;        FileInputStream file2 = null;        FileInputStream file3 = null;        try {            file1 = new FileInputStream("files/seq/seq1.txt");            file2 = new FileInputStream("files/seq/seq2.txt");            file3 = new FileInputStream("files/seq/seq3.txt");        } catch (FileNotFoundException e) {            System.out.println("文件未找到或者文件已经被删除...");            return;        }        Collection<FileInputStream> list = new ArrayList<FileInputStream>();        list.add(file1);        list.add(file2);        list.add(file3);        SequenceInputStream sis = new SequenceInputStream(Collections.enumeration(list));        //将文件进行了合并到序列流中,读取出来即可        try {            fout = new FileOutputStream("files/seq/seq.txt");            byte[] buf = new byte[1024];            int len = 0;            while((len=sis.read(buf))!=-1){                fout.write(buf,0,len);            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                file1.close();                file2.close();                file3.close();                fout.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}
0 0
原创粉丝点击