关于Java编程中使用RandomAccessFile进行大文件分割的探讨

来源:互联网 发布:手机提示网络错误 编辑:程序博客网 时间:2024/05/29 09:25

本人是Java初学者,目前仍然在打基础的阶段,在学习过程中碰到了 文件分割与合并的操作。话不多表,下面上代码




import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件切割类
 * size:被切割文件大小;blockSize: 切割文件块;finalBlockSize:最后一个文件块大小
 * @author chen
 *
 */
public class FileSplit {
    
    private String fileName;
   //文件总长度
   private long length;
   //文件分割的块数
   private long size;
   //文件每块大小
   private long blockSize;
   //文件读取路径
   public String filePath;
   //文件存储路径
   private List<String>blockPath;

   
   
   
   public FileSplit(){
       blockPath = new ArrayList<String>();
   }
   
public FileSplit(String filePath) {

    this(1024,filePath);
}

public FileSplit( long blockSize,String filePath) {
    this();
    this.blockSize =blockSize;
    this.filePath=filePath;
    init();
}
    
   //初始化方法
public void init(){
    File src= new File(filePath);
    this.fileName = src.getName();
    //增加文件非空,路径不存在等判断,增强程序的健壮性
    if(null==this.filePath||!src.exists()){
        return;
    }
    if(src.isDirectory()){
        return;
    }
      this.length=src.length();
    //修正每块大小
    if(this.blockSize>length){
        this.blockSize=length;
    }
    //确定块数
    this.size = (int)Math.ceil(length*1.0/this.blockSize);
}

//创建文件名称
public void initPathName(String destPath){
    for(int i=0;i<size;i++){
        this.blockPath.add(destPath+"/"+"part"+i+".txt");
    }
}
/**
 * 文件分割
 * @param destPath    分割后的文件存储路径
 */
public void split(String destPath){
    initPathName(destPath);
    long beginPos =0;
    long actualSize =this.blockSize;    
    for(int i=0;i<this.size;i++){
        //考虑最后一块大小
        if(i==size-1){
            actualSize =this.length-beginPos;
        }
        splitDetail(i,beginPos,actualSize);
        beginPos +=actualSize;           //下一次分割的起始点
    }
}
/**
 * 文件分割细节
 * @param nbx             分割文件第几个
 * @param beginPos    分割开始位置
 * @param actualSize   剩余文件实际长度
 */
public void splitDetail(int nbx,long beginPos,long actualSize){
    //1.创建源
    File src = new File(this.filePath);
    File dest = new File(this.blockPath.get(nbx));
    
    //选择流
    RandomAccessFile raf = null;
    BufferedOutputStream bos=null;
    try {
        raf = new RandomAccessFile(src,"r");
        bos = new BufferedOutputStream(new FileOutputStream(dest));
        //读取文件
        raf.seek(beginPos);
        //缓冲区
        byte[] flush = new byte[1024];
        //接受长度
        int len =raf.read(flush);
        bos.write(flush, 0, len);
    } catch (Exception e) {
    e.printStackTrace();
    }finally{
    try {
        FileUtils.Close(raf,bos);
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}
}


0 0