0

I tried this method to extracting zip files .

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

Inside the zip archive I have folders and files, and when I extract them I get everything in one place. Any idea how can I extract the folder and files as they looked before extraction?

1 Answers1

1

Looks like you remove all info about directories in this line of code

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

so, basically, if you have the following structure:

folder/file.ext 

your fileName variable will contain file.ext and you lose folder/

Try something like:

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);
Vasyl Glodan
  • 556
  • 1
  • 6
  • 22