文件分割:
随机流
RandomAccessFile
文件合并:
序列流:
SequenceInputStream
package com.hbsi.随机流_文件分割_合并;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
*面向对象思维文件分割、合并
* 随机读取和写入流 RandomAccessFile
*/
public class SplitFile {
//源头
private File file;
//目的地(文件夹)
private String dir ;
//所有分割后文件储存路径
private List<String>path;
//每块大小
private int blockSize;
//块数:多少块文件
private int size;
public SplitFile(String filepath, String dir, int blockSize) {
this.file = new File(filepath);
this.dir = dir;
this.blockSize = blockSize;
this.path = new ArrayList<String>();
//初始化
init();
}
//初始化方法
private void init(){
//总长度
long len =this.file.length();
//多少块
this.size =(int) Math.ceil( len*1.0/blockSize);//Math.ceil 向上取整数
//路径
for (int i=0;i<size;i++){
this.path.add(this.dir+"/"+i+"-"+this.file.getName());
}
//创建文件目录
File f = new File(this.dir);
if(!f.exists()){
f.mkdirs();
}
}
public void split() throws IOException {
//总长度
long len =file.length();
int beginPos = 0;//起始位置
int actuaiSize=(int) (blockSize>len?len:blockSize);//实际大小
for (int i=0;i<size;i++){
beginPos=i*blockSize;//每一块的起始位置
if (i==size-1){//最后一块
actuaiSize= (int) len;
}else {
actuaiSize= blockSize;//每一块的实际大小
len -=actuaiSize;//剩余量
}
splitDetail(i,beginPos,actuaiSize);
}
}
public void splitDetail(int i,int beginPos,int actuaiSize) throws IOException {
RandomAccessFile file = new RandomAccessFile(this.file,"r");
RandomAccessFile file1 = new RandomAccessFile(this.path.get(i),"rw");
// int beginPos = 2;//起始位置
// int actuaiSize=1026;//实际大小
//随机读取
file.seek(beginPos);//从第几个字节开始读取
byte [] a= new byte[1024];
int len=-1;
while ((len=file.read(a))!=-1){
if (actuaiSize>len){
file1.write(a,0,len);
actuaiSize -=len;//剩余需要读取的数量
}else {
file1.write(a,0,actuaiSize);
break;
}
}
file.close();
file1.close();
}
/**
* 文件合并
* @param
* @throws IOException
*/
public void merge(String hpath){
try{
OutputStream os = new BufferedOutputStream(new FileOutputStream(hpath,true));
Vector<InputStream> vi = new Vector<InputStream>();
SequenceInputStream sis =null;
for (int i=0;i<path.size();i++){
vi.add(new BufferedInputStream(new FileInputStream(path.get(i))));
sis = new SequenceInputStream(vi.elements());
int len=-1;
byte []bytes =new byte[1024];
while ((len=sis.read(bytes))!=-1){
os.write(bytes,0,len);
}
os.flush();
sis.close();
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
SplitFile sf = new SplitFile("src/ac.txt","src/wen",20);
sf.split();
sf.merge("src/wen/a.txt");
}
}