package com.heima.otherio;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;
public class Demo1_SequenceIS {
public static void main(String[] args) throws IOException {
String str1 = "a.txt";
String str2 = "b.txt";
String str3 = "c.txt";
String dest = "d.txt";
method0(str1,str2,dest);
method1(str1,str2,dest);
method1(str1,str2,str3,dest);
printFile(dest);
}
public static void method0(String src1,String src2,String destStr) throws IOException {
// 不使用序列流
FileInputStream fis1 = new FileInputStream(src1);
FileOutputStream fos = new FileOutputStream(destStr);
int b;
while ((b = fis1.read()) != -1) {
fos.write(b);
}
fis1.close();
FileInputStream fis2 = new FileInputStream(src2);
while((b = fis2.read()) != -1) {
fos.write(b);
}
fis2.close();
fos.close();
}
public static void method1(String src1, String src2,String destStr) throws IOException {
// 两个输入流的情况,使用序列流
FileInputStream fis1 = new FileInputStream(src1);
FileInputStream fis2 = new FileInputStream(src2);
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
FileOutputStream fos = new FileOutputStream(destStr);
int b;
while ((b=sis.read()) != -1) {
fos.write(b);
}
sis.close();
fos.close();
}
public static void method1(String src1,String src2, String src3, String destStr) throws IOException {
// 多个输入流,使用枚举,转序列流
// Enumeration<FileInputStream> en = new Enumeration();
Vector<FileInputStream> v = new Vector<>();
v.add(new FileInputStream(src1));
v.add(new FileInputStream(src2));
v.add(new FileInputStream(src3));
Enumeration<FileInputStream> en = v.elements();
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream(destStr);
int b;
while ((b = sis.read()) != -1) {
fos.write(b);
}
sis.close();
fos.close();
}
public static void printFile(String destStr) throws IOException {
// 打印目标文件的内容
BufferedReader br = new BufferedReader(new FileReader(destStr));
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
}
|
|