在Android上构建ZIP文件

时间:2018-04-25 02:26:47

标签: java android android-studio

我使用以下代码在我的外部存储上构建一个zip文件,唯一的问题是该文件无法在Windows PC上提取或用于除Android以外的任何其他内容,我想我已经缩小了问题到不存在的文件夹。

我的问题是我做错了什么来导致一种奇怪的zip格式?

/** 
 EXAMPLE USAGE : zipFolder("/sdcard0/downloads", "/sdcard0/Update.zip")
 **/
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 String firstFolder ="";
static private void addFileToZip(String path, String srcFile,
                                 ZipOutputStream zip) throws Exception
{

    if (firstFolder == "")
    {
        firstFolder = getLastPathComponent(path);
    }

    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.replace(firstFolder, "") + "/" + folder.getName()));
        while ((len = in.read(buf)) > 0)
        {
            zip.write(buf, 0, len);
        }
    }
}
public static String getLastPathComponent(String filePath)
{
    String[] segments = filePath.split("/");
    if (segments.length == 0)
        return "";
    String lastPathComponent = segments[segments.length - 1];
    return lastPathComponent;
}
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().replace(firstFolder, ""), srcFolder + "/" + fileName, zip);
        }
        else
        {
            addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
                         + fileName, zip);
        }
    }
}

0 个答案:

没有答案