java基础—文件的切割与合并

来源:互联网 发布:acm规则知乎 编辑:程序博客网 时间:2024/05/11 09:18


文件的切割与合并


import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Enumeration;import java.util.Vector;public class FileSplieDemos {public static void main(String[] args) throws Exception {File theReadPath = new File("C:\\Users\\Administrator\\Desktop\\测试文件夹\\凤舞九天.mp3");String  theOutPath ="C:\\Users\\Administrator\\Desktop\\测试文件夹\\abc\\";// 调用自定义方法将一个图片文件进行切割SplieFile(theReadPath,theOutPath,new File(".mp3"));//调用自定义方法将这些被分割的文件合并起String theMergerpathout = "C:\\Users\\Administrator\\Desktop\\测试文件夹\\abCOPY\\";String themergerInputpath="C:\\Users\\Administrator\\Desktop\\测试文件夹\\abc\\";String theoutformat = "MergerCopy.mp3";MergerFile(themergerInputpath,theMergerpathout,theoutformat);}private static void MergerFile(String themergerInputpath,String theMergerpathout, String theoutformat) throws Exception {// TODO Auto-generated method stubFile fil = new File(theMergerpathout);if(!(fil.isDirectory())){fil.mkdirs();}//将文件来源封装对象File file = new File(themergerInputpath);//获取所有块片的文件File[] names = file.listFiles();//创建一个容器,将所有的文件名字储存Vector<FileInputStream> v = new Vector<FileInputStream>();for(int x=0;x<names.length;x++){v.add(new FileInputStream(names[x]));}Enumeration<FileInputStream> en = v.elements();//合并多个流对象SequenceInputStream sis = new SequenceInputStream(en);//创建输出流对象BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(theMergerpathout+theoutformat));int len = 0;byte[] b = new byte[1024*1024];while((len=sis.read(b))!=-1){bos.write(b);bos.flush();}}private static void SplieFile(File file,String thepath,File format){// 通过字节流并联需要切割的文件对象,并加入缓冲技术提高效率System.out.println("切割文件功能启动");File fil = new File(thepath);if(!(fil.isDirectory())){fil.mkdirs();}BufferedInputStream bis = null;BufferedOutputStream bos = null;int number = 0;try {bis = new BufferedInputStream(new FileInputStream(file));//初使化输出路径byte[] b = new byte[1024*1024];    int len  = 0;    while((len = bis.read(b))!=-1)    {    number++;    bos = new BufferedOutputStream(new FileOutputStream(thepath+number+format));    bos.write(b);    bos.flush();        }} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}















1 0