假如我在本地磁盘下有如下文件,要求压缩打包:
我们可以使用java 提供的api:zipoutputstream
public class TestZip {
public static void main(String[] args) {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(new File("F:"
+ File.separator + "mbm.zip")));
File[] files = new File("F:" + File.separator + "test").listFiles();
int len = 0;
byte[] buffer = new byte[1024];
for (File file : files) {
ZipEntry entry = new ZipEntry(file.getName());
out.putNextEntry(entry);
FileInputStream in = new FileInputStream(file);
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
in.close();
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
输出结果为:
如果要求浏览器使用压缩的形式下载:
可把代码换成:
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ DateUtil.getCurrentDateStr("yyyyMMddhhmmss") + ".zip");<pre name="code" class="java"><span style="white-space:pre"> </span><pre name="code" class="java"><span style="white-space:pre"> </span>ZipOutputStream out=new ZipOutputStrean(response.getOutputStream());