Java 使url文件变成压缩包并将压缩包下载到浏览器上代码
时间: 2023-12-31 22:03:19 浏览: 85
url.zip_Java URL实现文件下载
5星 · 资源好评率100%
下面是将url文件转换成压缩包并下载到浏览器上的Java代码示例:
```java
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String urlString = "http://example.com/yourfile.ext";
String fileName = "yourfile.zip";
String mimeType = "application/zip";
response.setContentType(mimeType);
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
URL url = new URL(urlString);
try (InputStream is = url.openStream(); ReadableByteChannel rbc = Channels.newChannel(is)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
zos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
}
}
```
请确保替换 `urlString` 为您的 URL 文件和 `fileName` 为您想要下载的文件名。这个例子会将文件压缩成 zip 格式,如果您想要其他格式可以修改 mimeType。
阅读全文