java解压缩文件
2015-09-07 11:22
525 查看
压缩:
解压:
// 压缩 public static void zip(String zipFileName, String inputFile) throws Exception { File f = new File(inputFile); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); zip(out, f, null); System.out.println("zip done"); out.close(); } // 压缩 private static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fc = f.listFiles(); if (base != null) out.putNextEntry(new ZipEntry(base + "/")); base = base == null ? "" : base + "/"; for (int i = 0; i < fc.length; i++) { if (fc[i].getName().endsWith(".vmb")) { continue; } else { zip(out, fc[i], base + fc[i].getName()); } } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; while ((b = in.read()) != -1) out.write(b); in.close(); } }
解压:
// 解压 public static void unZipFiles(String filePath, String directoryPath) { try { File filezip = new File(filePath); ZipFile zipFile = new ZipFile(filezip); Enumeration enu = zipFile.entries(); String result = ""; while (enu.hasMoreElements()) { ZipEntry entry = (ZipEntry)enu.nextElement(); String name = entry.getName(); // 如果解压entry是目录,直接生成目录即可,不用写入,如果是文件,要讲文件写入 String path = directoryPath + File.separator + name; result = result + path + "<br/>"; File file = new File(path); if (entry.isDirectory()) { file.mkdirs(); } else { // 建议使用如下方式创建 流,和读取字节,不然会有乱码(当然要根据具体环境来定) InputStream is = zipFile.getInputStream(entry); byte[] buf1 = new byte[1024]; int len; if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } OutputStream out = new FileOutputStream(file); while ((len = is.read(buf1)) > 0) { String buf = new String(buf1, 0, len); out.write(buf1, 0, len); } is.close(); out.flush(); out.close(); } } } catch (Exception e) { e.printStackTrace(); } }
相关文章推荐
- Java的基本概念
- spring jar 包 用处功能:
- 按理来'|'说是个特殊字符,为啥split需要转义,用replace不需要转义
- JVM原理讲解和调优
- java异常处理机制finally中的return返回
- java注释量统计代码实现
- SpringMVC整合Mybatis做的一个简单的查询功能
- java 动态规划求解最长公共子序列&最长公共子串问题
- Spring优点
- eclipse 不断报错:Computing Git status for repository
- Java构造和解析Json数据的两种方法详解一
- Java算法-1.连通性问题
- android笔记(eclipse的使用)
- JAVA之JDK在64位系统默认开启压缩指针分析
- Eclipse中安装Jetty插件
- Myeclipse常见快捷键及配置
- json数据转换成java类
- windows 打包Java web项目内容实现一键安装
- 基于OAtuth2的新浪微博Java爬虫
- Struts 2防止表单重复提交