我从一个zip文件中检索了一个zip条目。
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();
}
这很好用,我的ZipEntry
没问题。
我的问题
如何将这些ZipEntries
的内容放入字符串中,因为它们是xml
和csv
个文件。
答案 0 :(得分:10)
您必须阅读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));
}
}
退出内部while
时保存StringBuilder
内容,然后重置。
答案 1 :(得分:2)
这种方法不会破坏Unicode字符:
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 :(得分:1)
使用set encoding(UTF-8)并且不创建字符串:
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);
}
答案 3 :(得分:0)
我会使用apache的IOUtils
ZipEntry entry;
InputStream input = params[0];
ZipInputStream zis = new ZipInputStream(input);
try {
while ((entry = zis.getNextEntry())!= null) {
String entryAsString = IOUtils.toString(zis, StandardCharsets.UTF_8);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IOUtils.closeQuietly(zis);