vishal
vishal

Reputation: 319

convert zip byte[] to unzip byte[]

I have byte[] of zip file. I have to unzip it without creating new file, and get byte[] of that unzip file. Please help me to do that

Upvotes: 12

Views: 22593

Answers (4)

valeesi
valeesi

Reputation: 195

If you have only one file in the zip, you could use the following code. If there are multiple files, just modify the if into a while.

public static byte[] toUnzippedByteArray(byte[] zippedBytes) throws IOException {
    var zipInputStream = new ZipInputStream(new ByteArrayInputStream(zippedBytes));
    var buff = new byte[1024];
    if (zipInputStream.getNextEntry() != null) {
        var outputStream = new ByteArrayOutputStream();
        int l;
        while ((l = zipInputStream.read(buff)) > 0) {
            outputStream.write(buff, 0, l);
        }
        return outputStream.toByteArray();
    }
    return new byte[0];
}

Upvotes: 3

sudhansu
sudhansu

Reputation: 91

public static List<ZipEntry> extractZipEntries(byte[] content) throws IOException {
    List<ZipEntry> entries = new ArrayList<>();
   
    ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(content));
    ZipEntry entry = null;
    while ((entry = zipStream.getNextEntry()) != null)
    {
        System.out.println( "entry: " + entry );
        ZipOutputStream stream= new ZipOutputStream(new FileOutputStream(new File("F:\\ssd\\wer\\"+entry.getName())));
        stream.putNextEntry(entry);
    }
    zipStream.close();
   
    return entries;
}

Upvotes: 7

coyer
coyer

Reputation: 4367

In case you need to deflate your zipped data and you are too lazy to deal with the streams, you can use the following code:

public byte[] deflate(byte[] data) throws IOException, DataFormatException {
    Inflater inflater = new Inflater();
    inflater.setInput(data);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
    byte[] buffer = new byte[1024];
    while (!inflater.finished()) {
        int count = inflater.inflate(buffer);
        outputStream.write(buffer, 0, count);
    }
    outputStream.close();
    byte[] output = outputStream.toByteArray();
    return output;
}

Upvotes: 3

Jesper
Jesper

Reputation: 206776

You can use ZipInputStream and ZipOutputStream (in the package java.util.zip) to read and write from ZIP files.

If you have the data in a byte array, you can let these read from a ByteArrayInputStream or write to a ByteArrayOutputStream pointing to your input and output byte arrays.

Upvotes: 14

Related Questions