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();
}
}