package chj.io1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
/**
* 文件分割
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
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) {
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());
}
}
/**
* 分割
* 1、计算每一块的起始位置和实际大小
* @throws IOException
*/
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 splitDetail(int i,int beginPos,int actualSize) throws IOException{
RandomAccessFile raf=new RandomAccessFile(this.src,"r");//有"r" "rw" "rws" "rwd"
RandomAccessFile raf2=new RandomAccessFile(this.destPaths.get(i),"rw");
raf.seek(beginPos);
byte[] flush=new byte[1024];
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();
}
/**
* 文件合并
* @param args
* @throws IOException
*/
public void merge(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];//缓冲容器
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) {//调用
SplitFile sf=new SplitFile("girl.png", "dest",1024*100);
// try {
// sf.split();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
try {
sf.merge("copyGirl.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
【JAVA】IO之文件合并(基于文件切割更改)
最新推荐文章于 2023-03-31 00:54:56 发布