SequenceInputStream 实现文件的切割与合并

来源:互联网 发布:知乎911是美国自导自演 编辑:程序博客网 时间:2024/05/17 04:57

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 stubFileInputStream 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>(){@Overridepublic boolean hasMoreElements() {// TODO Auto-generated method stubreturn it.hasNext();}@Overridepublic InputStream nextElement() {// TODO Auto-generated method stubreturn 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();}}


原创粉丝点击