I am trying to create separate files from ByteArrayOutputStream (Here byteOut is my ByteOutputStream). The following code does the job
final InputStream targetStream = new ByteArrayInputStream(byteOut.toByteArray());
final File destDir = new File(System.getProperty("user.dir"));
final byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(targetStream);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = new File(destDir, zipEntry.getName());
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zis.getNextEntry();
}
But I want to optimize the code, I tried using IOUtils.copy like this
final InputStream targetStream = new ByteArrayInputStream(byteOut.toByteArray());
final File destDir = new File(System.getProperty("user.dir"));
ZipInputStream zis = new ZipInputStream(targetStream);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = new File(destDir, zipEntry.getName());
try(InputStream is = new FileInputStream(newFile);
OutputStream fos = new FileOutputStream(newFile)) {
IOUtils.copy(is, fos);
}
zipEntry = zis.getNextEntry();
}
But the contents of the file aren't getting copied and I also get a FileNotFoundException in the second iteration. What am I doing wrong?