java zipfile将多级目录压缩
在 java 中,可以使用 java.util.zip 包中的 zipoutputstream 和 zipentry 类来压缩多级目录。
一个例子
展示如何递归地将一个目录及其所有子目录和文件压缩到一个 zip 文件中:
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
public class zipdirectory {
public static void main(string[] args) throws ioexception {
string sourcedirpath = "path/to/source/directory";
string zipfilepath = "path/to/output.zip";
try (zipoutputstream zipout = new zipoutputstream(new fileoutputstream(zipfilepath))) {
path sourcedir = paths.get(sourcedirpath);
files.walk(sourcedir)
.filter(path -> !files.isdirectory(path))
.foreach(path -> {
zipentry zipentry = new zipentry(sourcedir.relativize(path).tostring());
try {
zipout.putnextentry(zipentry);
files.copy(path, zipout);
zipout.closeentry();
} catch (ioexception e) {
system.err.println("failed to add file to zip: " + path);
e.printstacktrace();
}
});
}
}
}这个程序将遍历指定目录(包括子目录)的所有文件,并将它们添加到 zip 文件中。
步骤解析
- 使用 files.walk 方法递归遍历源目录。
- 对于每个非目录文件,创建一个相对路径的 zipentry。
- 将文件内容复制到 zipoutputstream。
请根据实际情况替换 sourcedirpath 和 zipfilepath。此外,请确保适当处理异常并关闭资源以避免资源泄漏。
java多级目录导出文件压缩包
//创建临时文件
file zipfile = file.createtempfile("test", ".zip");
path temp = files.createtempdirectory(null);
string srcimgpath = temp.tostring();
for( 循环 ){
string outimgpath = srcimgpath + "/aa/bb/cc";
file outimgfile = new file(outimgpath);
//如果文件夹不存在则创建
if (!outimgfile.exists() && !outimgfile.isdirectory()) {
outimgfile.mkdirs();
}
fileoutputstream outimgstream = new fileoutputstream(outimgpath + "/" + name);
imageio.write(bufimg, imgsuffix, outimgstream);
outimgstream.flush();
outimgstream.close();
}
ziputil.zip(srcimgpath, zipfile.getabsolutepath(), true);
string header = request.getheader("user-agent").touppercase();
string filename = "附件信息" + system.currenttimemillis() + ".zip";
if (header.contains("msie") || header.contains("trident") || header.contains("edge")) {
filename = urlencoder.encode(filename, "utf-8");
//ie下载文件名空格变+号问题
filename = filename.replace("+", "%20");
} else {
filename = new string(filename.getbytes(), "iso8859-1");
}
response.reset();
response.setcontenttype("text/plain");
response.setcontenttype("application/octet-stream; charset=utf-8");
response.setheader("location", filename);
response.setheader("cache-control", "max-age=0");
response.setheader("content-disposition", "attachment; filename=" + filename);
fileinputstream fis = new fileinputstream(zipfile);
bufferedinputstream buff = new bufferedinputstream(fis);
bufferedoutputstream out = new bufferedoutputstream(response.getoutputstream());
byte[] car = new byte[1024];
int l = 0;
while (l < zipfile.length()) {
int j = buff.read(car, 0, 1024);
l += j;
out.write(car, 0, j);
}
// 关闭流
fis.close();
buff.close();
out.close();
// 删除临时文件
zipfile.delete();
fileutil.deletedir(srcimgpath);总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论