62,614
社区成员
发帖
与我相关
我的任务
分享
public void split(String destName) throws IOException{
long beginPos =0;
long actualBlockSize=blockSize;
File dest = new File(destName);
dest.mkdir();
for(int i=0;i<size;i++){
if(i==(size-1)){
actualBlockSize =length-blockSize*(i-1);
}
splitDetail(i,beginPos,actualBlockSize,destName);
beginPos +=actualBlockSize;
}
}
/**
* @param idx 第几块
* @param beginPos开始位置
* @param actualBlockSize每块实际大小
* @throws IOException
*/
public void splitDetail(int idx,long beginPos,long actualBlockSize,String destName) throws IOException{
RandomAccessFile raf = new RandomAccessFile(filePath,"r");
OutputStream os = new FileOutputStream(new File(destName+"/"+blockPath.get(idx)));
raf.seek(beginPos);
byte[] bt = new byte[1024];
int len =0;
while((len=raf.read(bt))!=-1){
if(len>=actualBlockSize){
os.write(bt, 0,(int)actualBlockSize );
break;
}else{
os.write(bt, 0, len);
break;
}
}
public void mergeFile(String srcPath) throws IOException{
File dest = new File(srcPath+"/"+this.fileName);
//选择流
BufferedInputStream bis =null;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest,true));
for(int i=0; i<this.blockPath.size();i++){
String blockPathPart =srcPath+"/"+blockPath.get(i);
bis= new BufferedInputStream(new FileInputStream(new File(blockPathPart)));
byte[] bt = new byte[1024];
int len =0;
while((len=bis.read(bt))!=-1){
bos.write(bt, 0, len);
bos.flush();
}
}
bis.close();
bos.close();
}
public void deleteFile(File file){
if(file.exists()){
if(file.isDirectory()){
File[] files = file.listFiles(new FilenameFilter(){
@Override
public boolean accept(File file, String fileName) {
return fileName.contains(".part");
}
});
for(int i=0; i<files.length;i++){
System.out.println(files[i].getAbsolutePath());
deleteFile(files[i]);
}
}else {
file.delete();
}
}else{
System.out.println("文件不存在");
}
}
public static void main(String[] args) throws IOException {
SplitAndMergeFile file = new SplitAndMergeFile("F:/a.txt",7);
file.split("F:/文件分割后所在目录");
file.mergeFile("F:/文件分割后所在目录");
file.deleteFile(new File("F:/文件分割后所在目录"));
}