public static void main(String[] args) throws IOException {
//不使用SequenceInputStream
FileInputStream fis1 = new FileInputStream("aa.txt");
FileOutputStream fos = new FileOutputStream("cc.txt");
/*不用使用fos = new FileOutputStream("cc.txt",true);将原来文件内容清空的是new关键字,
在创建输出流,关联文件支出,会将原文件内容清空,创建之后,只要输出流 流不关闭,就会连续写入
而fos = new FileOutputStream("cc.txt",true)是确定是否清空关联文件之前文件中的原有内容*/
int b;
while ((b = fis1.read()) != -1) {
fos.write(b);
}
fis1.close();
FileInputStream fis2 = new FileInputStream("bb.txt");//尽量晚开早关
int b1;
while ((b1 = fis2.read()) != -1) {
fos.write(b1);
}
fis2.close();
fos.close();
//使用SequenceInputStream
SequenceInputStream sis =
new SequenceInputStream(new FileInputStream("aa.txt"), new FileInputStream("bb.txt"));
FileOutputStream fos1 = new FileOutputStream("cc.txt");
int b2;
while ((b2 = sis.read()) != -1) {
fos1.write(b2);
}
sis.close(); //sis在关闭的时候,会将构造方法中传入的流对象也都关闭
fos.close();
//整合多个输入流,可以用于整合歌曲串烧
Vector<FileInputStream> v = new Vector<>();
v.add(new FileInputStream("aa.txt"));
v.add(new FileInputStream("bb.txt"));
v.add(new FileInputStream("cc.txt"));
Enumeration<FileInputStream > en =v.elements();
SequenceInputStream sis2 =new SequenceInputStream(en); //将枚举中的输入流整合成一个
FileOutputStream fos2 = new FileOutputStream("dd.txt");
int b3;
while ((b3 = sis2.read())!=-1) {
fos2.write(b3);
}
sis2.close();
fos2.close();
} |
|