文件合并的原理和使用SequenceInputStream,实现文件碎片的合并
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");
// 创建集合
List<FileInputStream> list = new ArrayList<FileInputStream>();
for (int i = 1; i < 7; i++) {
// 保存所有的输入流
list.add(new FileInputStream(new File(path,i+".part")));
}
// 通过流工具类,获取一个枚举对象
Enumeration<FileInputStream> en = Collections.enumeration(list);
// 源
SequenceInputStream sis = new SequenceInputStream(en);
// 写入目的文件
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>();
// 获取读取流对象
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];
// 遍历集合,获取流对象
for (FileInputStream fis : list) {
int len = 0;
while((len = fis.read(buf)) != -1){
fos.write(buf, 0, len);
}
fis.close();
}
fos.close();
}
}
网友评论