文件合并的原理和使用SequenceInputStream殷费,實(shí)現(xiàn)文件碎片的合并
package com.zhaoqian.transstream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
public class Demo7 {
public static void main(String[] args) throws Exception {
//文件合并
// File file = new File("F:"+File.separator+"PartFiles"+File.separator+"my.properties");
// FileInputStream fsinfo = new FileInputStream(file);
// MergerFile_1();
MergerFile_2();
}
public static void MergerFile_2() throws Exception {
File path = new File("F:"+File.separator+"PartFiles");
// 創(chuàng)建集合
List<FileInputStream> list = new ArrayList<FileInputStream>();
for (int i = 1; i < 7; i++) {
// 保存所有的輸入流
list.add(new FileInputStream(new File(path,i+".part")));
}
// 通過(guò)流工具類仔引,獲取一個(gè)枚舉對(duì)象
Enumeration<FileInputStream> en = Collections.enumeration(list);
// 源
SequenceInputStream sis = new SequenceInputStream(en);
// 寫(xiě)入目的文件
FileOutputStream fos = new FileOutputStream(new File(path,"1.mp3"));
byte[] by = new byte[1024];
int len = 0;
while((len = sis.read(by))!=-1){
fos.write(by, 0, len);
}
fos.close();
sis.close();
}
public static void MergerFile_1() throws Exception {
List<FileInputStream> list = new ArrayList<FileInputStream>();
// 獲取讀取流對(duì)象
for (int i = 1; i < 7; i++) {
list.add(new FileInputStream("F:"+File.separator+"PartFiles"+File.separator+i+".part"));
}
FileOutputStream fos = new FileOutputStream(new File("F:"+File.separator+"PartFiles"+File.separator+"0.mp3"));
byte[] buf = new byte[1024*1024];
// 遍歷集合斥滤,獲取流對(duì)象
for (FileInputStream fis : list) {
int len = 0;
while((len = fis.read(buf)) != -1){
fos.write(buf, 0, len);
}
fis.close();
}
fos.close();
}
}