如何在android中递归输出Zip文件夹?

时间:2011-03-24 04:53:42

标签: android android-emulator

我可以压缩文件夹,但不能以递归方式压缩。请给我一个解决方案?

1 个答案:

答案 0 :(得分:4)

在java中(它是相同的)

static public void zipFolder(String srcFolder, String destZipFile)
        throws Exception {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;
    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);
    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();
}

static private void addFileToZip(String path, String srcFile,
        ZipOutputStream zip) throws Exception {
    File folder = new File(srcFile);
    if (folder.isDirectory()) {
        addFolderToZip(path, srcFile, zip);
    } else {
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
    }
}

static private void addFolderToZip(String path, String srcFolder,
        ZipOutputStream zip) throws Exception {
    File folder = new File(srcFolder);
    for (String fileName : folder.list()) {
        if (path.equals("")) {
            addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
        } else {
            addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
                + fileName, zip);
        }
    }
}

这里第一种方法(zipFolder)是主要方法,其他两种,只需压缩单个文件(addFileToZip)或文件夹(addFolderToZip)。