在不丢失文件夹的情况下提取 zip 存档

Extract zip archive without lossing folders

我试过这个方法来解压zip文件。

    public static Boolean unzip(String sourceFile, String destinationFolder)  {
    ZipInputStream zis = null;

    try {
        zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((ze = zis.getNextEntry()) != null) {
            String fileName = ze.getName();
            fileName = fileName.substring(fileName.indexOf("/") + 1);
            File file = new File(destinationFolder, fileName);
            File dir = ze.isDirectory() ? file : file.getParentFile();

            if (!dir.isDirectory() && !dir.mkdirs())
                throw new FileNotFoundException("Invalid path: " + dir.getAbsolutePath());
            if (ze.isDirectory()) continue;
            FileOutputStream fout = new FileOutputStream(file);
            try {
                while ((count = zis.read(buffer)) != -1)
                    fout.write(buffer, 0, count);
            } finally {
                fout.close();
            }

        }
    } catch (IOException  ioe){
        Log.d(TAG,ioe.getMessage());
        return false;
    }  finally {
        if(zis!=null)
            try {
                zis.close();
            } catch(IOException e) {

            }
    }
    return true;
}

在 zip 存档中,我有文件夹和文件,当我解压缩它们时,我将所有内容都集中在一个地方。 知道如何提取提取前的文件夹和文件吗?

您似乎删除了这行代码中有关目录的所有信息

fileName = fileName.substring(fileName.indexOf("/") + 1);

所以,基本上,如果你有以下结构:

folder/file.ext 

您的 fileName 变量将包含 file.ext 而您丢失 folder/

试试这样的:

String filePath = ze.getName();
fileName = filePath.substring(fileName.lastIndexOf("/") + 1);
folderPath = filePath.substring(0, fileName.lastIndexOf("/"));
File folder = new File(destinationFolder + folderPath)
if (!folder.exists()) {
    folder.mkdir();
}
File file = new File(folder, fileName);