使用java实现压缩软件的功能(分割文件)[57]
前言
本章将使用之前所学,实现一个分割文件的功能,其算法是压缩文件的算法
一、代码演示
private static void division(File file,long countSize){
if (file==null){return;}
//取出文件大小和每个文件要放置的大小,相除,得出要循环创建几个文件
int num= (int) (file.length()%countSize==0?file.length()/countSize:file.length()/countSize+1);
try {
//字节缓冲输入流
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
//字节缓冲输出流
BufferedOutputStream bop=null;
//创建一个未知大小的字节数组,用来存储读取的数据
byte[] bytes=null;
//读取数据的长度
int len=-1;
//循环读取数据的次数
int countF=0;
for (int i=0;i<num;i++){
//实例化字节缓冲输出流,并创建新的文件
bop=new BufferedOutputStream(new FileOutputStream("D:/files/testF"+(i+1)+".txt"));
//如果传入的文件字节大于1024就要多条读取,小于就直接读取一次
if (countSize<=1024){
bytes=new byte[(int) countSize];
countF=1;
}else {
bytes=new byte[1024];
//循环读取多少次
countF= (int) (countSize/1024);
}
//循环读取数据
while (countF>0 && (len=bis.read(bytes))!=-1){
bop.write(bytes,0,len);
//刷新输出流,并写入文件中
bop.flush();
countF--;
}
//有bug,如果有余数,就再读取一遍
if (countSize%1024!=0){
bytes=new byte[(int) (file.length()%countSize+1)];
len=bis.read(bytes);
bop.write(bytes,0,len);
bop.flush();
bop.close();
}
}
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
二.小结
本章使用java基础实现了分割文件的功能,后续会发布合并文件的功能,敬请期待;
有哪里不足或者有更好的建议,欢迎留言吐槽,有哪里不懂的小伙伴,可以私信我,我会一一答复,感谢认可,感谢支持!