java将工程目录下的文件夹压缩成zip包下载
时间: 2024-01-10 19:04:34 浏览: 80
您可以使用Java的ZipOutputStream类来压缩文件夹并生成zip文件,接着使用Java的FileInputStream类将生成的zip文件输出到response中,实现文件下载。以下是一个示例代码:
```java
// 设置要压缩的文件夹路径
String folderPath = "path/to/folder";
// 设置生成的zip文件名
String zipFileName = "example.zip";
// 创建zip输出流
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
// 创建缓冲输出流
BufferedOutputStream bufferedOut = new BufferedOutputStream(zipOut);
// 获取要压缩的文件夹下的所有文件
File folder = new File(folderPath);
File[] files = folder.listFiles();
// 遍历文件夹下的所有文件,将它们添加到zip输出流中
for (File file : files) {
FileInputStream fileIn = new FileInputStream(file);
BufferedInputStream bufferedIn = new BufferedInputStream(fileIn, 1024);
zipOut.putNextEntry(new ZipEntry(file.getName()));
byte[] buffer = new byte[1024];
int readCount = 0;
while ((readCount = bufferedIn.read(buffer)) != -1) {
bufferedOut.write(buffer, 0, readCount);
}
bufferedIn.close();
}
// 关闭zip输出流和缓冲输出流
bufferedOut.flush();
bufferedOut.close();
zipOut.close();
// 将生成的zip文件输出到response中,实现文件下载
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"");
FileInputStream fileIn = new FileInputStream(zipFileName);
BufferedInputStream bufferedIn = new BufferedInputStream(fileIn, 1024);
byte[] buffer = new byte[1024];
int readCount = 0;
while ((readCount = bufferedIn.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, readCount);
}
bufferedIn.close();
```
请注意,上述代码中的response是HttpServletResponse对象,您需要在web环境下使用此代码。如果您是在命令行环境下运行Java程序,则需要将生成的zip文件复制到您的本地文件系统中。
阅读全文