I am trying to get bytes of a specific file from an input stream with an archived file. I have Zipped file input stream data. From this I get ZipEntry and write the contents of each ZipEntry to the output stream and returning a byte buffer. This will return a buffer size output stream, but not the contents of each specific file. Is there any way I can convert a FileOutputStream to bytes or directly read the bytes of each ZipEntry?
I need to return the contents of ZipEntry as output. I do not want to write to the file, but just get the contents of each zip entry.
Thank you for your help.
public final class ArchiveUtils {
private static String TEMP_DIR = "/tmp/unzip/";
public static byte[] unZipFromByteStream(byte[] data, String fileName) {
ZipEntry entry = null;
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(data));
File tempDirectory = ensureTempDirectoryExists(TEMP_DIR);
try {
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
System.out.println("-" + entry.getName());
File file = new File(tempDirectory + "/"+ entry.getName());
if (!new File(file.getParent()).exists())
new File(file.getParent()).mkdirs();
OutputStream out = new FileOutputStream(entry.getName());
byte[] byteBuff = new byte[1024];
int bytesRead = 0;
while ((bytesRead = zis.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}
out.close();
if(entry.getName().equals(fileName)){
return byteBuff;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static File ensureTempDirectoryExists(String outputPath) {
File outputDirectory = new File(outputPath);
if (!outputDirectory.exists()) {
outputDirectory.mkdir();
}
return outputDirectory;
}
}