【问题标题】:Unzipping File does not retrieve folders解压文件不检索文件夹
【发布时间】:2014-09-04 20:33:41
【问题描述】:

我正在尝试将一些文件从 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;
}

【问题讨论】:

    标签: java android zip


    【解决方案1】:

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

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

    【讨论】:

    • 现在我觉得自己像个白痴。不会承认我在这上面花了多少时间。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 2023-04-04
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 2019-05-07
    • 2013-03-09
    • 1970-01-01
    相关资源
    最近更新 更多