首页 > 编程 > Java > 正文

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

2019-11-06 07:45:57
字体:
来源:转载
供稿:网友

★序列流 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(); } } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表