14

我已经从这样的 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 文件,我如何将它们的内容转换为字符串。

4

5 回答 5

13

你必须阅读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内容,并重置它。

于 2012-11-09T16:27:35.383 回答
5

使用定义的编码(例如 UTF-8)并且不创建字符串:

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());
}
于 2017-10-29T09:14:31.787 回答
4

这是一种不会破坏 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());
于 2016-03-30T13:46:17.067 回答
1

我会使用 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);
于 2020-01-16T14:54:12.160 回答
0

Kotlin 版本,但也可以在 Java 中使用

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
}
于 2021-12-09T04:52:13.547 回答