IO流--SequenceInputStream切割(合并)文件--优化(Properties集合相结合)

来源:互联网 发布:淘宝刷单的后果 编辑:程序博客网 时间:2024/05/22 14:30
 切割端的优化:
public static void splitFile(File file,File dir) throws IOException{/* * 切割文件优化:必须记录被切割文件的名称,以及切割出来的个数 *  */Properties pro=new Properties();//用读取流关联源文件FileInputStream fis=new FileInputStream(file);//定义一个1M的缓冲区,每次切割1M数据到临时文件中byte[] buf=new byte[SIZE];//创建目的FileOutputStream fos=null;//如果目录不存在则创建if(!dir.exists())dir.mkdir();int len=0;//切割文件的名字int count=1;while((len=fis.read(buf))!=-1){fos=new FileOutputStream(dir+"\\"+(count++)+".part");fos.write(buf,0,len);fos.close();}//将被切割文件的信息保存到properties集合中pro.setProperty("partcount", count+"");pro.setProperty("filename", file.getName());fos=new FileOutputStream(new File(dir,count+".properties"));pro.store(fos, "save split info");fis.close();fos.close();}

 


  自定义过滤器:

         

package cn.itheima.cway.IO;import java.io.File;import java.io.FilenameFilter;public class SuffixFilter implements FilenameFilter { private String suffix;public SuffixFilter(String suffix){this.suffix=suffix;}public boolean accept(File dir, String name) {// TODO Auto-generated method stubreturn name.endsWith(suffix);}}

优化后的合并:

 
public static void mergerFile(File dec) throws IOException{//获取到配置信息文件File[] files=dec.listFiles(new SuffixFilter(".properties"));if(files.length!=1)throw new RuntimeException(dec+"该目录下没有properties文件或者不唯一");//记录配置文件对象File confile=files[0];//获取该文件的信息Properties pro=new Properties();FileInputStream fis=new FileInputStream(confile);pro.load(fis);String filename=pro.getProperty("filename");int count=Integer.parseInt(pro.getProperty("partcount"));//获取该目录下的所有碎片文件File[] partFiles=dec.listFiles(new SuffixFilter(".part"));if(partFiles.length!=(count-1)){throw new RuntimeException("碎片文件个数不符合要求,应该是"+count+"个");}ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();for(int i=0;i<partFiles.length;i++){al.add(new FileInputStream(partFiles[i]));}//创建一个集合,用于存放读取到的part文件内容/*优化前ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();//将part文件读取到集合中for(int i=1;i<=4;i++){al.add(new FileInputStream(new File(dec,i+".part")));}*///合并后的文件名:File dir=new File(dec,filename);if(!dir.exists())dir.createNewFile();//把集合中的元素转换为枚举Enumeration<FileInputStream> en=Collections.enumeration(al);//创建序列化输入流,去读取part文件(碎片文件)的内容SequenceInputStream sis=new SequenceInputStream(en);//创建一个输出流,用于保存合并后的文件内容FileOutputStream fos=new FileOutputStream(dir);int len=0;byte[] buf=new byte[1024];while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}




public class Properties
extends Hashtable<Object,Object>

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。


0 0
原创粉丝点击