SequenceInputStream类的简单介绍。以及用该类合并集合文件数据的程序代码。

package SequenceInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class SequenceInputStreamDemo {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		/**
		 * 需求:将多个文件数据进行合并到一个文件中。
		 * 
		 * SequenceInputStream构造方法:
		 * SequenceInputStream sis = new SequenceInputStream(Enumeration<? extends InputStream> e);//枚举变量参数
		 */
//		show1();
		
//		show2();
		show3();

	}

	public static void show3() throws IOException {
		ArrayList<InputStream> al = new ArrayList<InputStream>();
		
		for(int i = 1 ; i<4 ; i++){
			al.add(new FileInputStream(i+".txt"));
		}
		Enumeration<InputStream> en = Collections.enumeration(al); 
		SequenceInputStream sis = new SequenceInputStream(en);//将三个数据源合并到一个数据源
		
		FileOutputStream fos = new FileOutputStream(new File("4.txt"));
		
		int len = 0;
		byte []bu = new byte[1024];
		while((len = sis.read(bu))!=-1){
			fos.write(bu, 0, len);
		}
		
		sis.close();
		fos.close();
	}

	public static void show2() throws IOException {
		ArrayList<InputStream> al = new ArrayList<InputStream>();
		for(int i = 1 ; i<4 ; i++){
			al.add(new FileInputStream(i+".txt"));
		}
		final Iterator<InputStream> it = al.iterator(); //内部类访问外部类中的成员变量,需要用final 修饰。
		Enumeration<InputStream> en = new Enumeration<InputStream>() {

			@Override
			public boolean hasMoreElements() {
				
				return it.hasNext();
			}

			@Override
			public InputStream nextElement() {
				
				return it.next();
			}			
		};
		
		SequenceInputStream sis = new SequenceInputStream(en);//将三个数据源合并到一个数据源
		
		FileOutputStream fos = new FileOutputStream(new File("4.txt"));
		
		int len = 0;
		byte []bu = new byte[1024];
		while((len = sis.read(bu))!=-1){
			fos.write(bu, 0, len);
		}
		
		sis.close();
		fos.close();
	}

	public static void show1() throws IOException {
		Vector<InputStream> v = new Vector<InputStream>();
		v.add(new FileInputStream("1.txt"));
		v.add(new FileInputStream("2.txt"));
		v.add(new FileInputStream("3.txt"));
		Enumeration<InputStream> en = v.elements();//获得枚举变量
		SequenceInputStream sis = new SequenceInputStream(en);//将三个数据源合并到一个数据源
		
		FileOutputStream fos = new FileOutputStream(new File("4.txt"));
		
		int len = 0;
		byte []bu = new byte[1024];
		while((len = sis.read(bu))!=-1){
			fos.write(bu, 0, len);
		}	
		sis.close();
		fos.close();
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值