问题
I am trying to get the bytes of a particular file from the zipped file input stream. I have the input stream data of the Zipped file. From this I am getting the ZipEntry and writing the contents of each ZipEntry to a output stream and returning the byte buffer. This will return the buffer size output stream, but not the contents of each particular file. Is there a way I can convert the FileOutputStream to bytes or directly read the bytes of each ZipEntry?
I need to return the ZipEntry contents as output. I dont want to write to a 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;
}
}
回答1:
Use a java.io.ByteArrayOutputStream like so -
ByteArrayOutputStream out = null; // outside of your loop (for scope).
// where you have a FileOutputStream.
out = new ByteArrayOutputStream(); // doesn't use entry.getName().
and then you can
return (out == null) ? null : out.toByteArray();
回答2:
The way that you read from a file in a ZIP file is you read from the ZipInputStream
while the last entry you got from getNextEntry
is the entry you want to read from.
来源:https://stackoverflow.com/questions/20793781/how-to-get-bytes-contents-of-each-zipfile-entry-from-zipinputstream-without-writ