SequenceInputStream实现文件的切割与合并
package file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
//文件切割合并
public class Demo11 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//文件切割
spilt(new File("D:\\music\\a.mp3"),"D:\\music\\");
System.out.println("文件切割完成....");
File srcFile = new File("D:\\music\\");
merge(srcFile,new File("D:\\music\\"),"b.mp3");
System.out.println("文件合并完成....");
}
private static void spilt(File src, String dir) throws IOException {
// TODO Auto-generated method stub
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos= null ;
int len = 0;
byte[] buf = new byte[1024*1024];
int count=1;
while((len = fis.read(buf)) != -1){
int i= count++;
fos = new FileOutputStream(dir+i+".mp3");
fos.write(buf, 0, len);
}
fos.close();
fis.close();
}
//切割的文件位置,合并后文件存放的文件位置,合并后的文件名
private static void merge(File srcFile,File destFile,String fileName) throws IOException {
// TODO Auto-generated method stub
//LinkedHashSet<InputStream> linkhashset
//如果文件路径不存在则创建
if(!destFile.isFile()){
destFile.mkdirs();
}
//获取并存放切割的所有文件
File[] files = srcFile.listFiles();
//将切割的文件放入LinkedHashSet集合中
LinkedHashSet<InputStream> linkedhashset =new LinkedHashSet<InputStream>();
for(int i=1 ;i< files.length;i++) {
linkedhashset.add(new FileInputStream(new File(srcFile,i+".mp3")));
}
final Iterator<InputStream> it = linkedhashset.iterator();
//SequenceInputStream合并流
SequenceInputStream sis = new SequenceInputStream(
//使用Eunmeration(列举)将文件列举出来
new Enumeration<InputStream>(){
@Override
public boolean hasMoreElements() {
// TODO Auto-generated method stub
return it.hasNext();
}
@Override
public InputStream nextElement() {
// TODO Auto-generated method stub
return it.next();
}
}
);
//合并文件
OutputStream fos = new FileOutputStream(new File(destFile,fileName));
int len = 0;
byte[] buf = new byte[1024];
while((len = sis.read(buf))!= -1){
fos.write(buf,0,len);
}
fos.close();
sis.close();
}
}