解压缩zip存档而不丢失文件夹

时间:2018-03-29 16:15:09

标签: java android android-studio unzip

我尝试了这种方法来解压缩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存档中我有文件夹和文件,当我提取它们时,我将所有内容放在一个地方。 任何想法如何在提取之前提取文件夹和文件?

1 个答案:

答案 0 :(得分: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);

尝试类似:

(rand() % (high - low)) + low