Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most readable way to write a ZipEntry to File?

Tags:

java

Given ZipFile zip, its ZipEntry entry and target File unzippedEntryFile, what is the most readable way to write entry to unzippedEntryFile?

I came up with following solution using Google Guava and Apache.Commons.IO:

InputSupplier<ByteArrayInputStream> entryInputSupplier = ByteStreams.newInputStreamSupplier(IOUtils.toByteArray(zip.getInputStream(entry)));
Files.copy(entryInputSupplier, unzippedEntryFile);

However, something tells me it can be made simplier.

Thanks,
Konrad

like image 643
Konrad Jamrozik Avatar asked Oct 19 '12 16:10

Konrad Jamrozik


2 Answers

I don't know what's not readable about your code, other than that you have a lot of nested calls. These can be broken out and assigned to local variables, which would make the code longer (but, in my opinion, a bit more readable).

You do seem to be processing the data twice -- once to read it into a byte array and again to copy it to the file. I haven't tested this, but it should work and cut the amount of data movement in half:

final InputStream zipStream = zip.getInputStream(entry);
InputSupplier<InputStream> supplier = new InputSupplier<InputStream>() {
    InputStream getInput() {
        return zipStream;
    }
};
Files.copy(supplier, unzippedEntryFile);

You could, in fact, create your own little class that implements InputSuppler<InputStream>. I'm surprised that I couldn't find one in the Guava library. (Apparently, others have been surprised at this as well.)

like image 102
Ted Hopp Avatar answered Oct 18 '22 10:10

Ted Hopp


Here is a quick link that might have all the possible scenarios for Zip file operation. If it is simple file operation, here is the tutorial from Sun. Am sure there are lot of open source API's. Here is the link to IO tutorial. Cheers

like image 27
sathish_at_madison Avatar answered Oct 18 '22 10:10

sathish_at_madison