IO流_SequenceInputStream(序列流)

时间:2021-09-13 16:35:06

SequenceInputStream(序列流):就是将多个流合成一个有序的流

需求:将三个文件中的数据合并到一个文件中

 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector; public class SequenceInputStreamDemo {
public static void main(String[] args) throws IOException { //该集合效率低,所以用ArrayList集合,但是该集合没有枚举,所以要自定义一个枚举
Vector<FileInputStream> v = new Vector<FileInputStream>(); v.add(new FileInputStream("F:\\0.txt"));
v.add(new FileInputStream("F:\\a.txt"));
v.add(new FileInputStream("F:\\info.txt")); Enumeration<FileInputStream> en = v.elements(); SequenceInputStream sis = new SequenceInputStream(en); FileOutputStream fos = new FileOutputStream("F:\\feng.txt"); byte[] buf = new byte[1024];
int len = 0;
while((len=sis.read(buf))!=-1){
fos.write(buf,0,len);
} sis.close();
fos.close();
} }
 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator; public class SequenceInputStreamDemo {
public static void main(String[] args) throws IOException {
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
al.add(new FileInputStream("F:\\0.txt"));
al.add(new FileInputStream("F:\\a.txt"));
al.add(new FileInputStream("F:\\info.txt")); Enumeration<FileInputStream> en = Collections.enumeration(al);//该方法的原理就是下面自定义的枚举
/* final Iterator<FileInputStream> it = al.iterator();
//自定义枚举,与ArrayList的迭代器结合使用
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
@Override
public boolean hasMoreElements() {
return it.hasNext();
}
@Override
public FileInputStream nextElement() {
return it.next();
}
};
*/ SequenceInputStream sis = new SequenceInputStream(en); FileOutputStream fos = new FileOutputStream("F:\\jian.txt"); byte[] buf = new byte[1024];
int len = 0;
while((len=sis.read(buf))!=-1){
fos.write(buf,0,len);
} sis.close();
fos.close(); } }