I’m calling onto some code that returns me an HTTP response. I can get the contents of the response which returns me a byte array. The bytes represent a zip file that I would like to extract and get the contents of a single file (the zip only contains one file).
Currently I have some messy code (I’ll need to clean it up if I keep it) that seems to work:
byte[] bytes = response.out.toByteArray();
ByteArrayInputStream input = new ByteArrayInputStream(bytes);
ZipInputStream zip = new ZipInputStream(input);
ByteArrayOutputStream output = new ByteArrayOutputStream();
zip.getNextEntry();
int data;
while ((data = zip.read()) != -1) output.write(data);
output.close();
zip.close();
input.close();
byte[] kmlBytes = output.toByteArray();
String contents = new String(kmlBytes, "UTF-8");
but was wondering whether there was a cleaner way to do the same thing because the above looks incredibly ugly.
In order to avoid “reinventing the wheel” and reduce clutter and to focus on your app’s business logic rather than low-level code like this, you can use Apache Commons Compress.