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();
}
}
https://zhhll.icu/2022/java基础/IO/3.zip压缩/
原文始发于微信公众号(bug生产基地):zip压缩
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/176384.html