java如何使用zip压缩实现读取写入
更新时间:2023年11月06日 10:51:12 作者:bug生产者
这篇文章主要为大家介绍了java如何使用zip压缩实现读取写入示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
zip压缩
zip文档可以以压缩格式存储一个或多个文件,可以使用ZipInputStream读取Zip文档,使用ZipOutputStream来写入到Zip文件中
ZipInputStream读取
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
// getNextEntry返回描述这个项的ZipEntry的对象
while ((ze = zin.getNextEntry()) != null) {
// getInputStream获取用于读取该项的输入流
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze), charset));
// 业务逻辑 todo
br.close();
// closeEntry关闭当前打开的项
zin.closeEntry();
}
zin.close();ZipOutputStream写入
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
File fileWillZip = new File(dir);
if (fileWillZip.exists()) {
// 需要压缩的文件是文件夹。需要递归进行压缩
if(fileWillZip.isDirectory()){
compressZip(zipOut,fileWillZip,fileWillZip.getName());
} else { // 是文件,直接压缩
zip(zipOut,fileWillZip,dir);
}
}
zipOut.closeEntry();
zipOut.close();
private void compressZip(ZipOutputStream zipOutput, File file, String suffixpath) {
File[] listFiles = file.listFiles();// 列出所有的文件
for(File fi : listFiles){
if(fi.isDirectory()){ // 如果是文件夹,继续递归
if(suffixpath.equals("")){
compressZip(zipOutput, fi, fi.getName());
}else{
compressZip(zipOutput, fi, suffixpath + File.separator + fi.getName());
}
}else{
zip(zipOutput, fi, suffixpath);
}
}
}
public void zip(ZipOutputStream zipOutput, File file, String suffixpath) {
try {
// 创建ZipEntry对象
ZipEntry zEntry = null;
if(suffixpath.equals("")){
zEntry = new ZipEntry(file.getName());
}else{
zEntry = new ZipEntry(suffixpath + File.separator + file.getName());
}
// putNextEntry将给定的ZipEntry中的信息写出到输出流,并定位用于写出数据的流,然后这些数据可以通过write方法写出到这个输出流中
zipOutput.putNextEntry(zEntry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int read = 0;
while((read = bis.read(buffer)) != -1){
zipOutput.write(buffer, 0, read);
}
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}以上就是java如何使用zip压缩实现读取写入的详细内容,更多关于java zip压缩读取写入的资料请关注脚本之家其它相关文章!
相关文章
JetBrains 产品输入激活码 Key is invalid 完美解决方案
JetBrains 系列产品(IDEA、Pycharm 等)使用本站破解教程 (opens new window),在输入激活码时,部分小伙伴反应说提示 Key is invalid 无法激活,今天小编给大家分享完美解决方案,感兴趣的朋友跟随小编一起看看吧2022-11-11
如何使用Comparator比较接口实现ArrayList集合排序
这篇文章主要介绍了如何使用Comparator比较接口实现ArrayList集合排序问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-12-12
解决Jackson解析嵌套类问题(MismatchedInputException)
这篇文章主要介绍了解决Jackson解析嵌套类问题(MismatchedInputException),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-06-06
Java中throws 与 throw 的区别与用法示例详解
本文给大家介绍Java中throws与throw的区别与用法示例详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧2025-09-09


最新评论