您的位置:首页 > 编程语言 > Java开发

java zipoutputstream 的使用

2015-12-24 23:13 585 查看
假如我在本地磁盘下有如下文件,要求压缩打包:



我们可以使用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());


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: