解压缩文件不会检索文件夹

时间:2014-09-04 20:33:41

标签: java android zip

我正在尝试将zip文件中的某些文件解压缩到与压缩文件具有相同文件结构的解压缩目录,但是使用getNextEntry()方法时遇到了困难。当我尝试在不存在的目录中创建文件时,它似乎只返回压缩文件中的文件而不是导致FileNotFoundException的文件夹。

例如,我的zip文件的第一级如下:

Folder 1 file2.txt Folder 2 Folder 3 file.txt

当我调用getNextEntry()时,返回的第一件事是file.txt,返回的第二件事是Folder 1/file2.txt。甚至嵌套的文件夹也被忽略了。这是以前的工作,但是,我不知道我做了什么打破它。

我传入的文件是位于内部存储中的压缩文件。任何帮助将不胜感激!

public boolean unZipAndEncrypt(File file) {
    boolean isSuccess = false;

    ZipInputStream zin = null;
    try {
        ZipFile zipFile = new ZipFile(file);
        FileInputStream fin = new FileInputStream(file);
        zin = new ZipInputStream(fin);
        ZipEntry ze;
        File contentDir = new File(bookDirectory, contentId);
        while ((ze = zin.getNextEntry()) != null) {
            String name = ze.getName();
            if (ze.isDirectory()) {
                File dir = new File(contentDir, name);
                dir.mkdirs();
                continue;
            }

            FileModel fileModel = new FileModel(zipFile.getInputStream(ze), name);
            if (!ze.getName().contains("cp_index")) {
                fileModel = encryptor.encrypt(fileModel);
            }
            File toWrite = new File(contentDir, fileModel.getFullPathName());
            toWrite.createNewFile();
            OutputStream fout = new FileOutputStream(toWrite);
            try {
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fileModel.getInputStream().read(buffer)) != -1) {
                    fout.write(buffer, 0, len);
                }
            } finally {
                fileModel.close();
                zin.closeEntry();
                fout.close();
            }

        }
        isSuccess = true;
    } catch (FileNotFoundException e) {
        Log.e(TAG, "", e);
    } catch (IOException e) {
        Log.e(TAG, "", e);
    } finally {
        file.delete();
        try {
            zin.close();
        } catch (IOException e) {
            Log.e(TAG, "", e);
        } catch (NullPointerException e) {
            Log.e(TAG, "", e);
        }
    }
    return isSuccess;
}

1 个答案:

答案 0 :(得分:1)

您可以在创建新文件之前创建目录:

toWrite.getParentFile().mkdirs();  // do before createNewFile()