Java将服务器上的文件下载到内存中,然后将文件打成压缩包zip,下载到浏览器代码
时间: 2023-04-10 09:02:41 浏览: 276
可以使用Java的ZipOutputStream类来实现将文件打成压缩包zip并下载到浏览器。以下是一个示例代码:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取要下载的文件路径
String filePath = "/path/to/file";
File file = new File(filePath);
// 设置响应头,告诉浏览器下载文件
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() + ".zip");
// 创建ZipOutputStream对象
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
// 将文件添加到压缩包中
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
fis.close();
zos.closeEntry();
// 关闭ZipOutputStream对象
zos.close();
}
}
```
在上面的代码中,我们首先获取要下载的文件路径,然后设置响应头,告诉浏览器下载文件。接着,我们创建ZipOutputStream对象,并将文件添加到压缩包中。最后,我们关闭ZipOutputStream对象,完成文件的下载。