/**
* 分割文件
* @author Administrator
*
*/
public class SpiltFile {
private String filePath;//文件路径
private int size;//块数
private String fileName;//文件名
private long length;//文件大小
private long blockSize;//分块大小
private List<String> blockPath;//所到路径
public SpiltFile() {
super();
blockPath =new ArrayList<String>();
}
public SpiltFile(String filePath) {
this(filePath,1024);
}
//调用这个构造
public SpiltFile(String filePath,long blockSize) {
this();
this.filePath=filePath;
this.blockSize=blockSize;
init();
}
public void init(){
File src=null;
if(null==filePath||!(src=new File(filePath)).exists()){
return;
}
if(src.isDirectory()){
return;
}
this.fileName=src.getName();
//计算块数 实际大小与每块大小
this.length =src.length();
//修正大小
if(this.blockSize>length){
this.blockSize=length;
}
//计算块数
size =(int) (Math.ceil(length*1.0/this.blockSize));
//initPathName();
}
//初始化路径名称
private void initPathName(String destPath){
for(int i=0;i<size;i++){
this.blockPath.add(destPath+"/"+this.fileName+".part"+i);
}
}
/**
* 文件的分割
* @param destPath
*/
public void split(String destPath){
//确定文件路径
initPathName(destPath);
long begingPos =0;//起始点
long actualBlockSize =blockSize;//实际大小
for(int i=0;i<size;i++){
if(i==size-1){
actualBlockSize=this.length-begingPos;
}
splitDetail(i,begingPos,actualBlockSize);
begingPos+=actualBlockSize;
}
}
/**
* 文件的分割
* @param idx
* @param beginPos
* @param actualBlockSize
*/
private void splitDetail(int idx,long beginPos,long actualBlockSize){
//建立连接
File src = new File(this.filePath);//原文件
File dest = new File(this.blockPath.get(idx));//目标文件地址
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=0;
while(-1!=(len=raf.read(flush))){
if(actualBlockSize-len>=0){
bos.write(flush, 0, len);
actualBlockSize-=len;//剩余量
}else{
bos.write(flush, 0,(int)actualBlockSize);
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
IOUtil.ioclose(bos,raf);
}
}
//测试
public static void main(String[] args) {
SpiltFile split =new SpiltFile("g:/ccc/testcopydirectory/xiaoce.txt",10);
System.out.println(split.size);
split.split("g:/ccc/testcopydirectory/testiostream/");
}
}
RandomAccessFile随机访问分割文件
最新推荐文章于 2021-07-18 20:45:28 发布