天天看点

JAVA中的IO流-SequenceInputStream类

Sequence:可以将文件进行合并.

例如:

将  1.txt , 2.txt, 3.txt 合并为一个文件

我在1.txt , 2.txt, 3.txt 分别写的是 一行1 和 两行2 和 三行3
           

例子(一):

需要:将要合并的文件放入一个枚举类中

这时就需要Vector集合

Vector: 是同步的…线程安全…但是效率相对较低

import java.io.*;
import java.uilt.Vector;

public class Demo {
	public static void main(String[] args) throws IOEception{
	
		Vector<FileInputStream> v = new Vector<FileInputStream>();
		v.add(new FileInputStream("1.txt"));
		v.add(new FileInputStream("2.txt"));
		v.add(new FileInputStream("3.txt"));
		
		Enumeration en = v.elements();//返回枚举
		
		SequenceInputStream sis = new SequenceInputStream (en);
		
		//把合并的写入到123.txt;
		FileOutputStream fos = new FileOutputStream("123.txt");
		
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = sis.read(buf)) != -1) {
			fos.write(buf,0,len);
			fos.flush();
		}
		
		sis.close();
		fos.close();
	}
}
           

运行结果:

JAVA中的IO流-SequenceInputStream类

例子(二):

因为我们使用Vector效率比较低, 所有我们使用ArrayList这个集合

因为ArrayList没有枚举方法…

所有使用Collections这个静态集合工具类

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;


public class Demo {
    public static void main(String[] args) throws IOException {
    
        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
        al.add(new FileInputStream("1.txt"));
        al.add(new FileInputStream("2.txt"));
        al.add(new FileInputStream("3.txt"));

        Enumeration<FileInputStream> en = Collections.enumeration(al);

        SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("123.txt");

        byte[] buf = new byte[1024];

        int len = 0;
        while((len = sis.read(buf)) != -1) {
            fos.write(buf,0,len);
        }

        fos.close();;

    }
}
           

运行结果:

与例子(一)相同