Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write ZipEntry Data To String

Tags:

java

android

I have retrieved a zip entry from a zip file like so.

InputStream input = params[0];
ZipInputStream zis = new ZipInputStream(input);

ZipEntry entry;
try {
    while ((entry = zis.getNextEntry())!= null) {

    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

This works fine and its getting my ZipEntry no problem.

My Question

How can I get the contents of these ZipEntries into a String as they are xml and csv files.

like image 335
StuStirling Avatar asked Nov 09 '12 16:11

StuStirling


3 Answers

you have to read from the ZipInputStream:

StringBuilder s = new StringBuilder();
byte[] buffer = new byte[1024];
int read = 0;
ZipEntry entry;
while ((entry = zis.getNextEntry())!= null) {
      while ((read = zis.read(buffer, 0, 1024)) >= 0) {
           s.append(new String(buffer, 0, read));
      }
}

When you exit from the inner while save the StringBuilder content, and reset it.

like image 123
Blackbelt Avatar answered Oct 10 '22 00:10

Blackbelt


With defined encoding (e.g. UTF-8) and without creation of Strings:

import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.io.ByteArrayOutputStream;
import static java.nio.charset.StandardCharsets.UTF_8;

try (
  ZipInputStream zis = new ZipInputStream(input, UTF_8); 
  ByteArrayOutputStream baos = new ByteArrayOutputStream()
) {
  byte[] buffer = new byte[1024];
  int read = 0;
  ZipEntry entry;
  while ((entry = zis.getNextEntry()) != null)
    while ((read = zis.read(buffer, 0, buffer.length)) > 0)
      baos.write(buffer, 0, read);
  String content = baos.toString(UTF_8.name());
}
like image 41
tellnobody1 Avatar answered Oct 10 '22 02:10

tellnobody1


Here is the approach, which does not break Unicode characters:

final ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));
final InputStreamReader isr = new InputStreamReader(zis);
final StringBuilder sb = new StringBuilder();
final char[] buffer = new char[1024];

while (isr.read(buffer, 0, buffer.length) != -1) {
    sb.append(new String(buffer));
}

System.out.println(sb.toString());
like image 40
Igor Bljahhin Avatar answered Oct 10 '22 01:10

Igor Bljahhin