首页

通过RandomAcessFile类实现文件的分割和合并,可以满足多线程下载机断点续传应用

标签:java,RandomAcessFile,操作文件file,多线程下载,断点续传,文件分割,文件合并     发布时间:2015-06-07   

前言

通过RandomAcessFile类能在文件的任意位置进行读写,可以根据分割设计规则再进行文件的合并,对于文件分割和合并功能可以用于多线程下载、断点续传等功能。

文件分割

实现文件分割功能方法,示例代码如下:

/**@b@ * 分割文件@b@ * @param srcName 源文件@b@ * @param splitTargetPath 分割文件所在目录@b@ * @param size:每一份大小,以KB为单位@b@ * @throw Exception@b@ **/@b@ public void cut(String srcName,String splitTargetPath,int size) throws Exception{@b@ @b@     size=size*1024;@b@     int maxx=0;@b@     @b@     //如果目录不存在,先创建出来@b@     File targetPath=new File(splitTargetPath);@b@     if(!targetPath.exists()){@b@         targetPath.mkdirs();@b@     }@b@     @b@     File srcFile=new File(srcName);@b@     int fileSize=(int)srcFile.length();//获取源文件大小@b@     int num;//分割文件个数@b@     @b@     RandomAcessFile inn=new RandomAcessFile(srcFile,"r");//打开要分割文件@b@     num=fileSize/size;@b@     @b@     int x=0,y=0;@b@     @b@     //对应分割的文件输出对应文件@b@     for(;y=num;y++){@b@         File targetFile=new File(splitTargetPath+File.separator+srcFile.getName()+y+"tmp");@b@         RandomAccessFile outt=new RandomAccessFile(targetFile,"rw");@b@         maxx+=size;@b@         for(;x<maxx;x++){@b@             outt.write(inn.read());@b@         }@b@     @b@         outt.close();@b@     }@b@     @b@     File targetFile=new File(splitTargetPath+File.separator+srcFile.getName()+y+"tmp");@b@     RandomAccessFile outt=new RandomAccessFile(targetFile,"rw");@b@     for(;x<fileSize;x++){@b@         outt.write(inn.read());@b@     }@b@     @b@     outt.close();@b@     inn.close():@b@ @b@ }

文件合并

实现文件合并功能方法,示例代码如下:

/**@b@ * 合并文件@b@ * @param srcName 源文件@b@ * @param splitTargetPath 分割文件所在目录@b@ * @param suffixName,分割后的文件后缀@b@ * @throw Exception@b@ **/@b@ public void unite(String srcName,String splitTargetPath,final String suffixName) throws Exception{@b@     File[] fs;@b@     @b@     File srcFile=new File(splitTargetPath);//当前已分割待合并的文件目录@b@     File targetFile=new File(srcName);//取的输出名@b@     RandomAcessFile outt=new RandomAcessFile(targetFile,"rw");@b@     @b@     //取得待合并的文件@b@     fs=srcFile.listFiles(new FilenameFilter(){@b@         public boolean accept(File dir,String name){@b@             String ss=new File(name).toString();@b@             return ss.endsWith(suffixName);@b@         }@b@          @b@     });@b@     @b@     //打印出文件@b@     for(int i=0;i<fs.length;i++){@b@         System.out.println(fs[i]);@b@     }@b@     @b@     //打开所有的文件准备进行合并@b@     @b@     for(int j=0;j<fs.length;j++){@b@         RandomAcessFile inn=new RandomAcessFile(fs[j],"r");@b@         int c;@b@         while((c=inn.read())!=-1)@b@             outt.write(c);@b@     }@b@     @b@     outt.close();@b@     @b@ }