简体   繁体   中英

Copy a file or multiple files form a zip file without actually unzipping it using perl or java

I have a couple of zip file which have multiple files and folders. It basically contains text files. Say extension 'a' and 'b'.

I want to separate the extension 'a' files and extension 'b' files into separate zip files, using a perl script or java code.

Instead of unzipping the files, can I just pick the contents and put it into another zip file. Is this even possible? Any help would be great.

The reason why I was wondering this is I have large number of zip files of large size, so if this is possible my code will be very efficient.

And any comments whether to use perl or java would be a bonus.

Thank you.

You can use the Java ZipFile class to read contents of a zip file, iterate over the entries in the zip and obtaining input streams for relevant entries. Using the ZipOutputStream it is possible to directly put the files into a new zip file - although they are decompressed/compressed in between. I don't know of a tool that can copy the zipped contents directly.

This might be done uzing Perl Archive::Zip library:

Actual oneliner might looks like the following:

perl -MArchive::Zip -e 'Archive::Zip->new("test.zip")->extractMember("testx.txt", "foo.txt");'

But I would like to provide full code with even some checks:

use Archive::Zip;

my $zip = Archive::Zip->new("test.zip");
my $file_path = "test.txt";

my $PARANOID = 1;
if ($PARANOID) {
    my $file = $zip->memberNamed($file_path);
    unless ($file) {
        die "File '$file_path' not found in the archive";
    }
}

$zip->extractMember($file_path, "extracted_file.txt");

Please note that you need to have Archive::Zip library installed:

cpan Archive::Zip

Or, if you are more confident with Perl ecosystem and have shiny cpanm utility installed:

cpanm Archive::Zip

I just found that zip on Unix has a --copy option which copies a file from one archive to another. I don't believe it decompresses the file in the process so it should be just what you (and I) need.

Syntax is:

$ zip source.zip "*.c" --copy --out destination.zip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM