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

来源:互联网 发布:中广核 知乎 编辑:程序博客网 时间:2024/04/26 00:24


java中文件的切割与合并操作


文件的切割 

/** *  * @param file要分割的文件  * @param paths要分割的文件保存的路径 * @param format要分割的文件保存的格式  * @throws Exception */public static void spilt(File file,String paths,String format) throws Exception  {  System.out.println("分割文件功能启动");  //将文件封装对象  //使用流关联文件对象  FileInputStream fis = new FileInputStream(file);  String name = file.getName();  //定义一个缓冲区  byte[] byt = new byte[1024*1024];  //创建一个目的地  FileOutputStream fos = null;  //设置分割文件储存路径  File fi = new File(paths);  //创建存储分割文件的文件夹,如果目的文件夹不存在,那么就创建  if(!fi.exists())  fi.mkdirs();  int len = 0;  int count = 1;  //创建一个储存数据的容器  Properties pro = new Properties();  //读取文件数据  while((len=fis.read(byt))!=-1)  {  //将文件命名并添加到流当中  fos = new FileOutputStream(new File(fi,name+(count++)+format));  fos.write(byt,0,len);  fos.close();  }  //将被切割的文件保存到pro集合中去  pro.setProperty( "partcount",count + "" );  pro.setProperty( "filename",file.getName());  fos = new FileOutputStream(new File(fi,count + ".properties" ));  //将prop集合中的数据存储到文件中  pro.store(fos, "save file info");  fis.close();  fos.close();  }  


要合并文件 的方法 

/** *  * @param file要合并的文件  * @param namess要合并的文件保存的名字 * @param paths要合并的文件保存的路径 * @param format要合并后保存的文件格式 * @throws Exception */public static void megrefile(File file,String namess,String paths,String format) throws Exception{System.out.println("合并文件功能启动");//获取指定目录下的文件以及指定格式的文件File[] files = file.listFiles(new Merger(format));//创建一个容器用来储存这些文件流对象Vector<FileInputStream> v = new Vector<FileInputStream>();for(int x=0;x<files.length;x++){//将获取的文件与流关联并添加到容器中去v.add(new FileInputStream(files[x]));}Enumeration<FileInputStream> en =v.elements();//合并多个流SequenceInputStream sis = new SequenceInputStream(en);//创建输出文件目录FileOutputStream fos = new FileOutputStream(paths+namess+format);int len = 0;byte[] byt = new byte[1024];while((len=sis.read(byt))!=-1){fos.write(byt);fos.flush();}sis.close();}


在使用的时候,可以先将一个文件进行切割,然后再进行合并 

//获取将需要切割的文件File  file = new File("E:\\myjava\\2015-6-14\\凤凰传奇-最炫民族风.mp36quot");//调用自定义切割文件功能spilt(file,"E:\\myjava\\2015-6-14\\abc",".mp3");//获取需要合并文件的目录File files = new File("E:\\myjava\\2015-6-14\\abc");//调用自定义合并文件功能megrefile(files,"myis","E:\\myjava\\2015-6-14\\121\\",".mp3");


//设置一个筛选指定格式文件的过渡器  public class Merger implements FilenameFilter  {  private String format;  Merger(String format)  {  this.format=format;  }  public boolean accept(File dir, String name)   {  //   return name.toLowerCase().endsWith(format);  }  }  




0 0
原创粉丝点击