Java 中施用gzip压缩、解压缩目录
Java 中使用gzip压缩、解压缩目录
/** * 压缩文件或目录<br/> * 将文件或者目录压缩为zip格式的压缩文件 * * @param commpressedFile 压缩后的文件 * @param preCommpressFile 需要压缩的文件或目录路径 * @return true | false */ public static boolean compress(String commpressedFile, String preCommpressFile) { boolean isSucc = true; File inputFile = new File(preCommpressFile); ZipOutputStream out; try { out = new ZipOutputStream(new FileOutputStream(commpressedFile)); log.debug("begin to compress file... ..."); compress(out, inputFile, inputFile.getName(), progess); log.debug("compressed successful"); out.close(); } catch (Exception e) { isSucc = false; log.error(e.toString(), e); } return isSucc; } /** * 递归压缩文件夹下的所有文件 * * @param out 输出流 * @param file 需要压缩的文件 * @param base 压缩后文件的父目录 * @throws IOException */ private static void compress(ZipOutputStream out, File file, String base) throws IOException { log.debug("compressing: " + file.getName() + "... ..."); if (file.isDirectory()) { File[] fs = file.listFiles(); base += "/"; log.debug("add folder: " + file.getName()); out.putNextEntry(new ZipEntry(base)); // 生成相应的目录 for (int i = 0; i < fs.length; i++) { // 对本目录下的所有文件对象递归遍历,逐个压缩 compress(out, fs[i], base + fs[i].getName(), progess); } } else { log.debug("add file: " + file.getName()); out.putNextEntry(new ZipEntry(base)); InputStream is = new FileInputStream(file); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) != -1) { out.write(buf, 0, len); } is.close(); } } /** * 解压缩文件<br/> * 解压缩zip格式的文件 * * @param zipFile 需要解压缩的文件 * @param desPath 解压后保存的目录 */ public static void decompress(String zipFile, String desPath) { // 建立输出流,用于将从压缩文件中读出的文件流写入到磁盘 OutputStream out = null; // 建立输入流,用于从压缩文件中读出文件 ZipInputStream is; File dir = new File(desPath); dir.mkdirs(); try { is = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry = null; while ((entry = is.getNextEntry()) != null) { log.debug("decompressing :" + entry.getName() + "... ..."); File f = new File(dir, entry.getName()); if (entry.isDirectory()) { log.debug("add filder :" + f.getName()); f.mkdir(); } else { log.debug("add file :" + f.getName()); // 根据压缩文件中读出的文件名称新建文件 out = new FileOutputStream(f); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) != -1) { out.write(buf, 0, len); } out.close(); } } is.close(); } catch (Exception e) { log.error(e.toString(), e); } }