Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - How to unzip all the files in a specific directory of a zip file?

Say I have a .zip file called Bundles.zip and directly inside Bundles.zip, there are a few files and a few folders. This is what the .zip looks like:

Bundles.zip top level screenshot

Now, I want to extract EVERYTHING from the Bundles folder. My program already knows the name of the folder that it needs to extract the files from, in this case, Bundles.

The Bundles folder inside the zip can have files, subfolders, files in the subfolders, basically anything, like this:

Bundles.zip inner folder screenshot

And I just need to extract everything from the Bundles folder to an output directory.

How can I accomplish this in Java? I have found answers which extract all the files and folders inside the zip, but I need to extract only a specific folder inside the zip, not everything.

Working code so far:

            ZipFile zipFile = new ZipFile(mapsDirectory + "mapUpload.tmp");
            Enumeration zipEntries = zipFile.entries();
            String fname;
            String folderToExtract = "";
            String originalFileNameNoExtension = originalFileName.replace(".zip", "");

            while (zipEntries.hasMoreElements()) {
                ZipEntry ze = ((ZipEntry)zipEntries.nextElement());

                fname = ze.getName();

                if (ze.isDirectory()) //if it is a folder
                {

                    if(originalFileNameNoExtension.contains(fname)) //if this is the folder that I am searching for
                    {
                        folderToExtract = fname; //the name of the folder to extract all the files from is now fname
                        break;
                    }
                }
            }

            if(folderToExtract == "")
            {
                printError(out, "Badly packaged Unturned map error:  " + e.getMessage());
                return;
            }


            //now, how do i extract everything from the folder named folderToExtract?

For the code so far, the originalFileName is something like "The Island.zip". Inside the zip there is a folder called The Island. I need to find the folder inside the zip file that matches the zip file's name, and extract everything inside that.

like image 471
user3149729 Avatar asked Apr 06 '15 20:04

user3149729


People also ask

How do you unzip all the contents in a zipped folder?

To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.

How do I unzip a file in a specific location?

By default, the unzip command extracts the zip file into your current working directory. If you want to extract the zipped files into a different directory, use the -d option followed by the path to the directory. Note: The directory you want to extract needs to be already in existence.

How do I unzip a folder in Java?

To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn't exists and any nested directories present in the zip file.


1 Answers

A much easier way to do that is using the NIO API of Java 7. I've just done that for one of my projects:

private void extractSubDir(URI zipFileUri, Path targetDir)
        throws IOException {

    FileSystem zipFs = FileSystems.newFileSystem(zipFileUri, new HashMap<>());
    Path pathInZip = zipFs.getPath("path", "inside", "zip");
    Files.walkFileTree(pathInZip, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
            // Make sure that we conserve the hierachy of files and folders inside the zip
            Path relativePathInZip = pathInZip.relativize(filePath);
            Path targetPath = targetDir.resolve(relativePathInZip.toString());
            Files.createDirectories(targetPath.getParent());

            // And extract the file
            Files.copy(filePath, targetPath);

            return FileVisitResult.CONTINUE;
        }
    });
}

Voilà. Much cleaner than using ZipFile and ZipEntry, and it has the additional benefit of being re-usable for copying folder structure from ANY type of file system, not only for zip files.

like image 91
LordOfThePigs Avatar answered Oct 27 '22 10:10

LordOfThePigs