文件切割
public static void split(File src,String filepath,int size) {
long length=src.length();//计算文件长度(字节数)
int number=(int) Math.ceil(src.length()*1.0/size);//计算需要分割成几块
File[] file=new File[number];//建立文件
for(int i=0;i<number;i++) {
file[i]=new File(filepath+"/"+i);
}
for(int beginPos=0,now=0;now<number;now++,beginPos+=size) {//选中切割位置
if(now==number-1) {
IOUtils.splitDes(beginPos,(int)(src.length()-beginPos), src, file[now]);//到了最后一个的时候,需要传正确的大小
}
else {
IOUtils.splitDes(beginPos,size,src,file[now]);//调用切割方法(采用封装来简化代码)
}
}
}
private static void splitDes(int beginPos,int size,File src,File dest) {
try(RandomAccessFile raf=new RandomAccessFile(src,"r");//采用可以自由选择位置的流,r是可读,rw是可写可读
OutputStream out=new BufferedOutputStream(new FileOutputStream(dest))) {//其实也可以选择打印流,无所谓
int actualsize=1024*10000;//大小自定义,大一点貌似比较好,好调试
raf.seek(beginPos);//选择起始位置
byte[] destbyte=new byte[actualsize];
do {//do-while好像比较方便一点,自定义吧
if(size>=actualsize) {
raf.read(destbyte);
out.write(destbyte);
out.flush();//别忘了这个
size-=actualsize;//循环条件的改变
}
else {
raf.read(destbyte, 0, size);
out.write(destbyte,0,size);
out.flush();
size-=size;//也可以size=0,这里是最后一步
}
}while(size>0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
这里的分割结果只是一堆字节文件,可以通过修改后缀名的方式来还原。不过一般来说我觉得分割后的文件都是一堆乱码,这一串代码只能把字节分割,做不到真正意义上的分割
文件的合并
这个没什么难度,就是文件的复制,不过是可以append的复制而已
public static void merge(String destpath,File...files) {
//输入流,输出流的选择
try {
OutputStream out=new BufferedOutputStream(new FileOutputStream(destpath,true));
for(int i=0;i<files.length;i++) {//多个输入流的创建
try(InputStream in=new BufferedInputStream(new FileInputStream(files[i]));) {
int len=-1;//下面就是标准模板
byte[] target=new byte[1024*100];
while((len=in.read(target))!=-1) {
out.write(target, 0, len);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
catch(Exception e) {
e.getStackTrace();
}
}
感觉代码可以写的更漂亮一点,但是因为只是复习一下学过的知识的缘故,感觉能用就可以了。。。