尚学堂189 集文件

package com.zzsxt.file.fenkuai;

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

public class Fenkuai02 {

    private File src;

    private String destDir;
    //所有分割后文件的路径
    private List<String> destPaths;

    //每块的大小
    private int blockSize;
    //块数
    private int blockCount;

    public Fenkuai02 (String src,String destDir,  int blockSize){
        this.src=new File(src);
        this.destDir=destDir;
        this.blockSize=blockSize;
        this.destPaths=new ArrayList<String>();

    }

    private void init(){
        long length = this.src.length();

        this.blockCount =(int)(length%blockSize==0?length/blockSize:length/blockSize+1) ;
        for(int i=0;i<blockCount;i++){
            this.destPaths.add(this.destDir+"/"+i+"--"+this.src.getName());

        }
    }



    /**
     * 计算每一块的起始位置,以及实际大小
     * 分割。
     */
   public void split() throws IOException {

       //文件的大小
       long length = src.length();


       //起始位置 和 每块的实际大小
       int startPos=0;
       //
       int  actualSize=(int)(blockSize>length?length:blockSize) ;

       for(int i=0;i<blockCount;i++){

           startPos=i*actualSize;
           if(i==blockCount-1){
               actualSize=(int)length;
           }else {
               actualSize=blockSize;
               length-=blockSize;
           }
           System.out.println( "第"+i+"块,从"+startPos+"开始,到"+actualSize+"结束"  );
           solit(i,startPos,actualSize);
       }

   }

    private  void solit(int i, int startPos, int actualSize) throws IOException {
        RandomAccessFile rf = new RandomAccessFile( this.src,"r");
        RandomAccessFile rw = new RandomAccessFile( this.destPaths.get(i),"rw");

        rf.seek(startPos);

        byte[] flush =new byte[actualSize];  //定义每块的大小
        int temp;
        while ( (temp= rf.read(flush))!=-1  ){
            if( actualSize>temp){
                rw.write(flush,0,temp);

                actualSize-=temp;
            }else {

              rw.write(flush,0,actualSize);
                break;

            }

        }
        rw.close();
        rf.close();

    }


    public static void main(String[] args) throws IOException {


        Fenkuai02 fenkuai02 = new Fenkuai02("aCopy.png", "d:/lianxi", 1024);
        fenkuai02.init();
        fenkuai02.split();
   }





}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值