Reputation: 265
I have a byte array that its contents is filled from a zip file.I want to get each files in that zip archive as a separate byte array in memory to access them randomly. I don't want to write anything in sdcard and keep the arrays in memory.
I've searched and found this. Here is my code:
protected Map<String,ZipFile> ZipDic;
class ZipFile{
public byte[] contents;
public String name;
public long size;
}
public makeDictionary(byte[] zipFileArray) {
try {
InputStream is = new ByteArrayInputStream(zipFileArray);
ZipInputStream zipInputStream = new ZipInputStream(is);
ZipDic = new HashMap<>();
ZipEntry ze = null;
while ((ze = zipInputStream.getNextEntry()) != null) {
ZipFile zf=new ZipFile();
zf.name="/testepub/"+ze.getName();
zf.size=ze.getSize();
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = is.read(buf, 0, 1024)) != -1) {
output.write(buf, 0, n);
}
zf.contents=output.toByteArray();
}catch (Exception ex){
ex.printStackTrace();
zf.contents=null;
}
ZipDic.put(zf.name,zf);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
my problem is when the while
loop does the first loop, zf.contents
is a byte array that its size is alittle less than zipFileArray
and in the second loop gets exception :
java.util.zip.ZipException: CRC mismatch.
How can I get each files in zipFileArray
separately as uncompressed byte arrays?
Upvotes: 2
Views: 3957
Reputation: 1026
Change
while ((n = is.read(buf, 0, 1024)) != -1) {
output.write(buf, 0, n);
}
into
while ((n = zipInputStream.read(buf, 0, 1024)) != -1) {
output.write(buf, 0, n);
}
Upvotes: 1