当前位置: 代码迷 >> 综合 >> 支持递归压缩文件夹-org.apache.tools.zip.ZipEntry
  详细解决方案

支持递归压缩文件夹-org.apache.tools.zip.ZipEntry

热度:16   发布时间:2024-01-13 02:39:35.0

问题场景

压缩文件夹或者文件,要求可以压缩到文件夹里面

CODE

jar包

package zip;import java.io.*;import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;;/*** Created on 2017/6/7* Author: youxingyang.*/
public class ZipTest {
    private static int DEFAULT_BUFFER_SIZE = 16 * 1024;public static void main(String[] args) {//要压缩的路径String zipPath = "E://TESTZIP//新建文件夹";//生成的压缩文件位置String tmpFileName = "test.zip";String strZipPath = "E://TESTZIP" + File.separator + tmpFileName;try {ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));File file = new File(zipPath);zip(out, file, file.getName());out.close();if (new File(strZipPath).length() > 0) {System.out.println("success zipped");}} catch (IOException e) {e.printStackTrace();}}/*** 压缩文件或者文件夹-worker* @param zOut zip输出流* @param file 文件或者文件夹* @param name 文件或者文件夹名称*/public static void zip(ZipOutputStream zOut, File file, String name) {try {if (file.isDirectory()) {File[] listFiles = file.listFiles();name += "/";zOut.putNextEntry(new ZipEntry(name));for (File listFile : listFiles) {zip(zOut, listFile, name + listFile.getName());}} else {zOut.putNextEntry(new ZipEntry(name));writeFile(zOut,file);}zOut.setEncoding("GBK");} catch (Exception e) {e.printStackTrace();}}/*** 写文件到out* @param zOut* @param file* @throws IOException*/public static void writeFile(ZipOutputStream zOut,File file) throws IOException{byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];FileInputStream in = new FileInputStream(file);int len;while ((len = in.read(buffer)) > 0) {zOut.write(buffer, 0, len);zOut.flush();}in.close();}
}
  相关解决方案