Reid Mac
Reid Mac

Reputation: 2489

Unzipping File does not retrieve folders

I am trying to unzip some files from a zip file to an unzipped directory with the same file structure as the zipped file, but am having difficulty with the getNextEntry() method. It seems to be returning only the files in the zipped file and not the folders which is causing a FileNotFoundException when I try to create a file in a directory that doesn't exist.

For example the first level of my zip file is like the following:

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

When I call getNextEntry() the first thing returned is file.txt, the second thing returned is Folder 1/file2.txt. Even the nested folders are being ignored. This was previously working, however, I'm not sure what I did to break it.

The file I'm passing in is a zipped file located in internal storage. Any help will be much appreciated!

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;
}

Upvotes: 0

Views: 98

Answers (1)

Darrell
Darrell

Reputation: 2045

You could create the directory before creating the new file:

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

Upvotes: 1

Related Questions