Java实现文件zip压缩功能
程序员文章站
2022-05-07 17:30:26
...
Java实现文件zip压缩功能
网上看了一些例子,好像写的都不太清楚如意,便自己写了一个,如下,可以参考:
public void compression(String zipFileName,File targetFile){
try {
//压缩输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
//加快缓存流速度
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream);
//递归压缩,实现文件夹和文件都以压缩
zip(zipOutputStream,targetFile,targetFile.getName(),bufferedOutputStream);
//输出完成
bufferedOutputStream.flush();
//关闭输出流
bufferedOutputStream.close();
//关闭zip输出流
zipOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//进行zip压缩
private void zip(ZipOutputStream zipOutputStream,File targetFile,String targetName,BufferedOutputStream bufferedOutputStream){
if(targetFile.isDirectory()){
//获取到所有文件
File[] files = targetFile.listFiles();
//如果文件为空
if(files.length == 0){
try {
zipOutputStream.putNextEntry(new ZipEntry(targetName+"/"));
} catch (IOException e) {
e.printStackTrace();
}
}
//遍历文件列表,实现递归压缩
for (File file : files){
zip(zipOutputStream,file, targetName+"/"+file.getName(),bufferedOutputStream);
}
}else{
try {
//创建压缩条目
zipOutputStream.putNextEntry(new ZipEntry(targetName));
//读取文件
FileInputStream fileInputStream = new FileInputStream(targetFile);
//读取到缓冲流
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] bytes = new byte[1024];
int length = -1;
if((length = bufferedInputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,length);
}
//关闭输出流
bufferedOutputStream.flush();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OK!问题解决!不会的给我私信!
觉得有帮助的可以关注一波!经常分享编程踩坑经验!
上一篇: java实现图片压缩功能