Java分割文件

 * 作用:RandomAccessFile综合练习
 *
 *@author hby_gd@163.com
 *@date 2/6/2020 下午9:04
 */

import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 文件的分割
 * 1、属性:源文件路径、大小,目标文件所在目录、大小、个数、名字
 * 2、分割 每次循环,确定分割的起点和终点
 */

public class SplitFile {
    private String sourcePath;
    private long length;
    
	//给定默认输出目录
    private String endPath = "D:/test/words";
    private long size;
    private  int nums;
    private List<String> nameList;

    public int getNums(){return nums;}
    public long getLength(){return length;}
    public long getSize(){return size;}

    public SplitFile() {
        nameList = new ArrayList<String>();
    }

    public SplitFile(String sourcePath,long size){
        this();
        this.sourcePath = sourcePath;
        this.size = size;
        init();
    }

    public SplitFile(String sourcePath){
        this(sourcePath,10l);
    }

    /**
     * 初始化,将其他属性赋值
     */
    private void init(){
        File file = new File(sourcePath);
        //判断源文件是否合法
        if(null==sourcePath||!file.exists()||file.isDirectory()){
            System.out.println("目标文件不存在或有误");
            return;
        }

        this.length = file.length();
        this.nums = (int)(Math.ceil(((double)length)/size));
        for (int i = 0; i < nums; i++) {
            nameList.add("文件"+i+".txt");
        }
    }

    /**
     * 文件分割
     */
    public void split() throws IOException {
        long startPoint = 0;

        for (int i = 0; i < nums; i++) {
            if(i==nums-1){
                splitDetail(i,startPoint,length-startPoint);
                return;
            }
            splitDetail(i,startPoint,size);
            startPoint+=size;
        }
    }
    //单个分割实现
    public void splitDetail(int i,long startpoint,long endpoint) throws IOException {
        File file = new File(endPath,nameList.get(i));
        OutputStream ops = new BufferedOutputStream(new FileOutputStream(file));
        File sourceFile = new File(sourcePath);
        RandomAccessFile rdf = new RandomAccessFile(sourceFile,"r");
        rdf.seek(startpoint);
        byte[] flush = new byte[1024];

        int len = 0;
        while (-1!=(len =rdf.read(flush))){
            ops.write(flush,0,(int)endpoint);
            ops.flush();
        }
        rdf.close();
    }
}

使用了面向对象的思想,将文件分割抽象化。运用了IO流相关知识。
过程中出现的问题
1.分割的起点和终点的确认
RandomAccessFile类提供的seek方法,确定了缓冲流的起点,所以在 flush 缓冲数组 的终点应该是要求的分割后文件的实际大小size,而不是在源文件中的位置。
2.Math.ceil方法的使用
ceil(double a),参数要求为double类型,如果直接传入long类型的length和size,则会返回一个错误的答案,需要将length强转为double类型,避免出错。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值