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());
我们可以使用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());
相关文章推荐
- Java数字图像处理基础知识
- Java快速排序原理理解
- 模拟收音机播放音乐
- Java [Leetcode 169]Majority Element
- java enum(枚举)使用详解 + 总结
- struts2
- Java Unicode 编码互转
- Java API —— 异常
- 基于Spring Boot构建的Spring MVC快速入门
- Intellij idea 配置JDK
- Java NIO1:I/O模型概述
- java线程池使用
- 从头认识java-14.4 Java提供的数组的实用功能(2)
- myeclipse 10和myeclipse2015软件和破解工具
- Java的单例模式
- 为javasript中对象与json串之间转换的总结。
- java 读取 excel
- Java中Runnable和Thread的区别
- JDK,JRE,JVM,SDK,API,ADT,OOM,ANR
- 8个超有用的Java測试工具和框架