java 压缩文件夹

/**
* @param src 要压缩的文件夹目录
* @param des 压缩完保存路径
* @throws IOException
*/
public void zipCompress(String src, String des) throws IOException {
ZipOutputStream out = null;
try {
CheckedOutputStream cusm = new CheckedOutputStream(
new FileOutputStream(des), new Adler32());
out = new ZipOutputStream(new BufferedOutputStream(cusm));
fileZip(new File(src), out, “”);
} finally {
if (out != null) {
out.close();
}
}
}

/**
 * @param file 要压缩的文件夹目录
 * @param out
 * @param base 重定义文件名
 * @throws IOException
 */
private static void fileZip(File file, ZipOutputStream out, String base)
        throws IOException {
    if (file.isFile()) {
        if (base.length() > 0) {
            out.putNextEntry(new ZipEntry(base));
        } else {
            out.putNextEntry(new ZipEntry(file.getName()));
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(
                new FileInputStream(file), "ISO8859_1"));

        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();

    } else if (file.isDirectory()) {
        File[] subFiles = file.listFiles();
        if (null != base && !base.equals(""))
            out.putNextEntry(new ZipEntry(base + File.separator));
        base = base.length() != 0 ? base + File.separator : "";

        for (File subFile : subFiles) {
            fileZip(subFile, out, base + subFile.getName());
        }
    }

}

猜你喜欢

转载自blog.csdn.net/u011128560/article/details/82016682