一)SequenceInputStream介绍
运行原理:序列流可以把多个字节输入流整合成一个。它从一个有序的输入流集合开始,从第一个读取到文件的结尾,然后从第二个文件读取,依此类推,直到最后一个输入流达到文件的结尾。
初始化构造方法:
1、SequenceInputStream(Enumeration<? extends InputStream> e)
初始化新创建 SequenceInputStream通过记住参数,它必须是一个 Enumeration对象,它运行时类型是InputStream 。
2、SequenceInputStream(InputStream s1, InputStream s2)
按照顺序读取s1和s2的字节输入流内容。
二)SequenceInputStream场景详解
场景一:把两个字节输入流的文件,复制到一个新文件中
/**
* 场景一:把两个字节输入流的文件,复制到一个新文件中
*/
public static void method1() {
InputStream in1 = null;
InputStream in2 = null;
SequenceInputStream seq = null;
OutputStream out = null;
try {
in1 = new FileInputStream(new File("D:\\io\\a.txt"));
in2 = new FileInputStream(new File("D:\\io\\b.txt"));
seq = new SequenceInputStream(in1, in2);
out = new FileOutputStream(new File("D:\\io\\c.txt"));
byte[] bytes = new byte[1024*8];
int len = 0;
while((len = seq.read(bytes)) != -1){
out.write(bytes, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in1 != null) {
in1.close();
}
if (in2 != null) {
in2.close();
}
if (seq != null) {
seq.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
场景二:把多个字节流的文件,复制到一个新文件中,可参考SequenceInputStream源码
/**
* 场景二:把多个字节流的文件,复制到一个新文件中,可参考SequenceInputStream源码
*/
public static void method2() {
SequenceInputStream seq = null;
OutputStream out = null;
try {
// 多个文件
Vector<InputStream> v = new Vector<InputStream>();
v.add(new FileInputStream(new File("D:\\io\\a.txt")));
v.add(new FileInputStream(new File("D:\\io\\b.txt")));
v.add(new FileInputStream(new File("D:\\io\\c.txt")));
// 枚举类型
Enumeration<InputStream> enums = v.elements();
// 序列流
seq = new SequenceInputStream(enums);
out = new FileOutputStream(new File("D:\\io\\d.txt"));
byte[] bytes = new byte[1024*8];
int len = 0;
while((len = seq.read(bytes)) != -1){
out.write(bytes, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (seq != null) {
seq.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
识别二维码关注个人微信公众号
本章完结,待续,欢迎转载!
本文说明:该文章属于原创,如需转载,请标明文章转载来源!