Writing ZipEntry Data to a String

I got a zip record from a zip file like this.

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 great and I have no problem with ZipEntry .

My question

How to get the contents of these ZipEntries into a string, since they are xml and csv files.

+6
source share
3 answers

you should read from 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 internal while save the contents of StringBuilder and reset it.

+6
source

Here is an approach that 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()); 
+2
source

With encoding set (UTF-8) and without creating strings:

 import java.util.zip.ZipInputStream; import java.util.zip.ZipEntry; import java.io.ByteArrayOutputStream; import static java.nio.charset.StandardCharsets.UTF_8; String charset = "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(charset); } 
0
source

All Articles