How do you pipe an inputstream to a zipped file as it's read in with Java?
-
02-07-2019 - |
Question
I'm wanting to execute a program and as it runs read in it's output and pipe out the output into a zipped file. The output of the program can be quite large so the idea is to not hold too much in memory - just to send it to the zip as I get it.
Solution
ZipOutputStream targetStream = new ZipOutputStream(fileToSaveTo);
ZipEntry entry = new ZipEntry(nameOfFileInZipFile);
targetStream.putNextEntry(entry);
byte[] dataBlock = new byte[1024];
int count = inputStream.read(dataBlock, 0, 1024);
while (count != -1) {
targetStream.write(dataBlock, 0, count);
count = inputStream.read(dataBlock, 0, 1024);
}
In otherwords:
- You create a ZipOutputStream, giving it the file you want to write to.
You create a ZipEntry, which constitutes a file within that zip file. i.e. When you open myFile.zip, and there are 3 files in there, each file is a ZipEntry.
You put that zipEntry into your ZipOutputStream
- Create a byte buffer to read your data into.
- Read from your inputStream into your byte buffer, and remember the count.
- While the count is not -1, write that byte byffer to your zipStream.
- Read the next line.
Close out your streams when you are done. Wrap it in a method as you see fit.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow