RandomAccessFile:随机访问
文件分割与合并
面向对象的思想,封装分割文件。
要素
//源头
private File src;
//目的地(文件夹)
private String destDir;
//所有分割后的文件存储路径
private List destPaths;//将所有的文件存入一个容器中。
//每块的大小
private int blockSize;
//块数
private int size;
public class SplitFile {
//源头
private File src;
//目的地(文件夹)
private String destDir;
//所有分割后的文件存储路径
private List<String> destPaths;//将所有的文件存入一个容器中。
//每块的大小
private int blockSize;
//块数
private int size;
public SplitFile(String srcPath, String destDir, int blockSize) {
super();
this.src = new File(srcPath);
this.destDir = destDir;
this.blockSize = blockSize;
this.destPaths=new ArrayList<String>();
//初始化
init();
}
private void init() {
//总长度
long len=this.src.length();
//块数
this.size=(int)Math.ceil(len*1.0/this.blockSize);
//路径
for(int i=0;i<size;i++) {
this.destPaths.add(this.destDir+"/"+i+"-"+this.src.getName());
}
}
private void splitDetail(int i, int beginPos, int actualSize) throws IOException {
RandomAccessFile raf=new RandomAccessFile(this.src,"r");
RandomAccessFile raf2=new RandomAccessFile(this.destPaths.get(i),"rw");
raf.seek(beginPos);//从第三个位置开始读取内容。
byte[] flush=new byte[1024];//10k,创建读取数据时的缓冲,每次读取的字节个数。
int len=-1;//接受长度;
while((len=raf.read(flush))!=-1) {
//表示当还没有到文件的末尾时
//字符数组-->字符串,即是解码。
if(actualSize>len) {//获取本次所有的内容
raf2.write(flush,0,len);
actualSize-=len;
}else {
raf2.write(flush,0,actualSize);
break;
}
}
raf2.close();
raf.close();
}
public void split() throws IOException {
//总长度。
long len=src.length();
int beginPos=0;
int actualSize=(int)(blockSize>len?len:blockSize);
for(int i=0;i<size;i++) {//循环读取每一块的值
beginPos=i*blockSize;
if(i==size-1) {//如果是最后一块
actualSize=(int)len;//最后的剩余量
}else {//如果不是最后一块
actualSize=blockSize;
len-=actualSize;
}
splitDetail(i,beginPos,actualSize);
}
}
public void MergeFile(String destPath) throws IOException {
//输出流
OutputStream os=new BufferedOutputStream(new FileOutputStream(destPath,true));
//文件追加
//输入流.有多个源头
for(int i=0;i<destPaths.size();i++) {
InputStream is=new BufferedInputStream(new FileInputStream(destPaths.get(i)));
byte[] flush=new byte[1024];//10k,创建读取数据时的缓冲,每次读取的字节个数。
int len=-1;//接受长度;
while((len=is.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
is.close();
}
os.close();
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//源头,。
SplitFile sf=new SplitFile("copy.jpg","dest",1024*10);
sf.split();
sf.MergeFile("a.jpg");
}
}