Write Zipentry Data To String
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.
Solution 1:
you have to read from the ZipInputStream
:
StringBuilder s = new StringBuilder();
byte[] buffer = newbyte[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.
Solution 2:
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;
importstatic java.nio.charset.StandardCharsets.UTF_8;
try (
ZipInputStreamzis=newZipInputStream(input, UTF_8);
ByteArrayOutputStreambaos=newByteArrayOutputStream()
) {
byte[] buffer = newbyte[1024];
intread=0;
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null)
while ((read = zis.read(buffer, 0, buffer.length)) > 0)
baos.write(buffer, 0, read);
Stringcontent= baos.toString(UTF_8.name());
}
Solution 3:
Here is the approach, which does not break Unicode characters:
finalZipInputStreamzis=newZipInputStream(newByteArrayInputStream(content));
finalInputStreamReaderisr=newInputStreamReader(zis);
finalStringBuildersb=newStringBuilder();
finalchar[] buffer = newchar[1024];
while (isr.read(buffer, 0, buffer.length) != -1) {
sb.append(newString(buffer));
}
System.out.println(sb.toString());
Solution 4:
I would use apache's IOUtils
ZipEntry entry;
InputStreaminput= params[0];
ZipInputStreamzis=newZipInputStream(input);
try {
while ((entry = zis.getNextEntry())!= null) {
StringentryAsString= IOUtils.toString(zis, StandardCharsets.UTF_8);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IOUtils.closeQuietly(zis);
Solution 5:
Kotlin version but can be used in Java as well
val zipInputStream = ZipInputStream(inStream)
var zipEntry = zipInputStream.nextEntry
while(zipEntry != null) {
println("Name of file : " + zipEntry.name)
val fileContent = String(zipInputStream.readAllBytes(), StandardCharsets.UTF_8)
println("File content : $fileContent")
zipEntry = zipInputStream.nextEntry
}
Post a Comment for "Write Zipentry Data To String"