package Split;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
public class Splitinit {
private String filename;
private long lenth;
private String destpath;
private String filePath;
private long blockSize;
private int size;
List<String> blockpath;
public Splitinit(){
blockpath=new ArrayList<String>();
}
public Splitinit(String filePath,String destpath){
this(filePath,1024,destpath);
}
public Splitinit(String filePath,long blockSize,String destpath){
this();
this.blockSize=blockSize;
this.filePath=filePath;
this.destpath=destpath;
init();
}
public void init(){
File src=null;
if((this.filePath ==null)||!((src=new File(this.filePath)).exists()))
return;
this.lenth =src.length();
if(src.isDirectory())return;
if(this.blockSize>src.length()) this.blockSize=src.length();
this.size=(int)Math.ceil(src.length()*1.0/this.blockSize);
this.filename=src.getName();
blockname();
}
private void blockname(){
for(int i=0;i<size;i++){
blockpath.add(this.filename+".patr"+i);
}
}
public void split( ) throws Exception{
File dest=new File(destpath);
long begin=0;
long actualsize=blockSize;
for(int i=0;i<this.size ;i++){
if(i==size-1){
actualsize=this.lenth-begin;
}
splitdetail(i,begin,actualsize);
begin+=actualsize;
}
}
private void splitdetail(int index,long begin,long actualsize) throws Exception{
File src = new File(this.filePath); //源文件
File dest = new File(this.blockpath.get(index)); //目标文件
//2、选择流
RandomAccessFile raf =new RandomAccessFile(src,"r");
OutputStream bos=new FileOutputStream(dest,true);
String s=null;
//读取文件
raf.seek(begin);
//缓冲区
byte[] flush = new byte[5];
//接收长度
int len =0;
while(-1!=(len=raf.read(flush))){
if(actualsize>len) {bos.write(flush, 0, len);
actualsize-=len;}
else{
bos.write(flush, 0, (int)actualsize);
break;
}
bos.flush();
s=new String(flush,0,len);
}
}
public static void main(String[] args) throws Exception {
Splitinit s =new Splitinit("F:cc.txt",12,"F:/");
s.split();
System.out.println(s.blockpath);
}
}
|