文件的分割与合并
程序员文章站
2022-04-09 17:29:32
...
import java.io.*;
import java.util.*;
public class MySplitFile {
private String srcPath;//被分割的文件目录
private String destPath;//分割的目的文件夹
private String fileName;//分割的文件名
private long begin;//读取起点
private long length;//被分割文件的长度
private long blockSize;//分割块的大小
private List<String> blockPath;//分割文件的目录
private int size;//被分割的块数
public MySplitFile() {
blockPath = new ArrayList<>();
}
public MySplitFile(String srcPath,String destPath,long blockSize) {
this();
this.blockSize = blockSize;
this.srcPath=srcPath;
this.destPath=destPath;
init();
}
public void init(){
File src=null;
if(null==this.srcPath||!(src=new File(srcPath)).exists()){
return;
}
if(src.isDirectory()) {
return;
}
this.fileName=src.getName();
length=src.length();
this.size=(int)(Math.ceil(length*1.0/blockSize));//计算共有多少块
splitPath(destPath);
}
public void splitPath(String destPath){
for(int i=0;i<size;i++){
blockPath.add(destPath+"/"+fileName+i+".txt");//分割文件的目录
}
}
public MySplitFile(String filePath,String destPath) {
this(filePath,destPath,1024);//默认分割块的大小为1024个字节
}
public void split(){
splitPath(destPath);
long actualBlockSize=blockSize;
for(int i=0;i<size;i++){
if(i==size-1){
actualBlockSize=length-begin;//最后一块的大小
}
splitDetail(i,actualBlockSize);
begin+=actualBlockSize;//计算分割起点
}
}
public void splitDetail(int i,long actualBlockSize) {
//数据源
File src=new File(srcPath);
//选择流
RandomAccessFile raf=null;
BufferedOutputStream bos=null;
try {
raf=new RandomAccessFile(src,"r");
bos=new BufferedOutputStream(new FileOutputStream(new File(blockPath.get(i))));
raf.seek(begin);
byte[] flush=new byte[1024];
int len=0;
while (-1!=(len=raf.read(flush))){
if(actualBlockSize>len){
bos.write(flush,0,len);
actualBlockSize-=len;
}else{
bos.write(flush,0,(int)actualBlockSize);
break;
}
}
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bos.close();
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void merge(String destPath){//文件的合并
//数据源
for(int i=0;i<size;i++){
mergeDetail(blockPath.get(i),destPath);
}
}
public void mergeDetail(String src,String destPath){
//数据源
File file=new File(src);
File dest=new File(destPath);
//选择流
InputStream is=null;
BufferedOutputStream bos=null;
try {
is=new BufferedInputStream(new FileInputStream(file));
bos=new BufferedOutputStream(new FileOutputStream(dest,true));
byte[] flush=new byte[1024];
int len=0;
while(-1!=(len=is.read(flush))){
bos.write(flush,0,len);
}
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MySplitFile mySplitFile=new MySplitFile("D:/test.txt","D:/a/b",10);
//mySplitFile.split();
mySplitFile.merge("D:/test2.txt");
}
}
上一篇: Python3更全面的支持中文
下一篇: 第十二章:IO流