java zip 批量打包(java.util包和apache.tools包)
2016-07-29 15:15
447 查看
/** * 文件批量打包 * @param zipPath 打包路径 * @param files 批量文件 */ public void zipOut(String zipPath,File[] files){ byte[] buffer = new byte[1024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath)); for(int i=0;i<files.length;i++) { FileInputStream fis = new FileInputStream(files[i]); out.putNextEntry(new ZipEntry(files[i].getName())); int len; //读入需要下载的文件的内容,打包到zip文件 while((len = fis.read(buffer))>0) { out.write(buffer,0,len); } out.closeEntry(); fis.close(); //删除文件,可以不删 files[i].delete(); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("生成zip文件成功"); }
以上为java.util包zip的压缩方式,弊端是不能修改编码。下面介绍apache.tools包zip的压缩方式。
/** * 创建ZIP文件 * @param zipPath 生成的zip文件存在路径(包括文件名) * @param files 写入的文件 */ public static void zipOut(String zipPath,File[] files) { FileOutputStream fos = null; ZipOutputStream zos = null; try { fos = new FileOutputStream(zipPath); zos = new ZipOutputStream(fos); writeZip(files, zos); } catch (FileNotFoundException e) { System.out.println("创建ZIP文件失败"); } finally { try { if (zos != null) { zos.close(); } } catch (IOException e) { System.out.println("创建ZIP文件失败"); } } } /** * 写入内容 * @param files * @param zos */ private static void writeZip(File[] files, ZipOutputStream zos) { for(int i=0;i<files.length;i++) { if(files[i].exists()){ FileInputStream fis=null; DataInputStream dis=null; try { fis=new FileInputStream(files[i]); dis=new DataInputStream(new BufferedInputStream(fis)); ZipEntry ze = new ZipEntry(files[i].getName()); zos.putNextEntry(ze); //添加编码,如果不添加,当文件以中文命名的情况下,会出现乱码 // ZipOutputStream的包一定是apache的ant.jar包。JDK也提供了打压缩包,但是不能设置编码 zos.setEncoding("GBK"); byte [] content=new byte[1024]; int len; while((len=fis.read(content))!=-1){ zos.write(content,0,len); zos.flush(); } } catch (FileNotFoundException e) { System.out.println("创建ZIP文件失败"); } catch (IOException e) { System.out.println("创建ZIP文件失败"); }finally{ try { if(dis!=null){ dis.close(); } }catch(IOException e){ System.out.println("创建ZIP文件失败"); } } } } }
相关文章推荐
- org.apache.log4j.Logger实现用户数据收集(非系统日志收集)
- 一张图看懂开源许可协议,开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
- 一张图看懂开源许可协议,开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
- svn+apache安装配置
- Spark 概念学习系列之如果Apache Spark集群中没有分布式系统,则会?(六)
- 2.如何修改apache的默认端口
- Apache-Commons CSV文件的读和写
- Apache服务器最新版下载、安装及配置(win版)
- Apache Commons工具包介绍
- Apache shiro+springmvc+springdata+jpa+swagger(零配置文件使用)
- hbase错误:Org.apache.hadoop.ipc.RemoteException:User:client is not allowed to impersonate root
- org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist:
- 解决Exception: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z 等一系列问题
- Apache Spark的部署环境的小记
- Windows OS上安装运行Apache Kafka教程
- apache-net ftpclient ftp死锁的问题
- 千呼万唤始出来:Apache Spark2.0正式发布
- apache24 php
- Apache Hadoop creator — Doug Cutting
- CentOs 安装配置 Apache