Ideas were combined
(1) Construction of objects; (2) to read the file; (3) writing, using a set of required; (4) closing the flow
merging 1
Here we merge two documents, use OutputStream class Write (byte [] , 0, len) method. Use ArrayList collection to store files to facilitate the merger.
public static void test4() throws IOException {
String name1 = "E:" + File.separator + "a" + File.separator + "d.txt";
String name2 = "E:" + File.separator + "a" + File.separator + "e.txt";
String name3 = "E:" + File.separator + "a" + File.separator + "f.txt";
InputStream in1 = new FileInputStream(name1);
InputStream in2 = new FileInputStream(name2);
OutputStream out = new FileOutputStream(name3);
ArrayList<InputStream> list = new ArrayList<InputStream>();
list.add(in1);
list.add(in2);
byte[] b = new byte[1024];
int num;
for (int i = 0; i < 2; i++) {
InputStream in = list.get(i);
while ((num = in.read(b)) != -1) {
out.write(b, 0, num);
}
in.close();
}
out.close();
System.out.println("ok");
}
The results: e.txt is hello; d.txt is China
merge 2
use enum
//构建路径
String name1 = "E:" + File.separator + "a" + File.separator + "d.txt";
String name2 = "E:" + File.separator + "a" + File.separator + "e.txt";
String name3 = "E:" + File.separator + "a" + File.separator + "f.txt";
//读取文件
InputStream in1 = new FileInputStream(name1);
InputStream in2 = new FileInputStream(name2);
OutputStream out = new FileOutputStream(name3);
//放入集合
ArrayList<InputStream> list = new ArrayList<InputStream>();
list.add(in1);
list.add(in2);
// 枚举合并
Enumeration<InputStream> e = Collections.enumeration(list);
SequenceInputStream input = new SequenceInputStream(e);
int num;
byte[] b = new byte[1024];
while ((num = input.read(b)) != -1) {
out.write(b, 0, num);
}
out.close();
System.out.println("ok");
}
The same results.
Summary
enumeration for merging multiple files