0

我有一个下面提到的 java 类,它提取一个 zip,并将其内容一一转换为字符串并打印到控制台。
问题是,当 zip 中的文件很大时,大约 80KB。没有显示整个内容(只有 3/4 的数据被转换为字符串并显示在控制台中)。
其次,下面提到的代码在两者之间引入了空/空格,如果文件大小很小~1KB

下面提到的代码有什么问题。

 public static void main(String[] args) throws Exception {
    byte[] buf = new byte[1024];
    final int BUFFER = 1024;
    String fName = "c:\\DOC00001.zip";
    ZipInputStream zinstream = new ZipInputStream(
            new FileInputStream(fName));
    ZipEntry zentry = zinstream.getNextEntry();

    while (zentry != null) {            
    byte data[] = new byte[BUFFER];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while ((zinstream.read(data, 0, BUFFER)) != -1) {
        out.write(data);
    }       
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer, "UTF-8");
    String response = writer.toString();
    System.out.println(response);
    zentry = zinstream.getNextEntry();
    }
    zinstream.close();
}
4

1 回答 1

0

read方法不保证读取一个完整的缓冲区;返回已读取的字节数。从 zip 文件或任何InputStream一般文件中提取数据的正确方法是:

byte[] data = new byte[BUFFER];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = zinstream.read(data, 0, BUFFER)) != -1) {
    out.write(data, 0, bytesRead);
}

或者,由于您已经在使用IOUtils

ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(zinstream, out);

或者,假设您ByteArrayOutputStream只写入 a 以稍后写入字符串,您可以ByteArrayOutputStream完全跳过:

while (zentry != null) {
  StringWriter writer = new StringWriter();
  IOUtils.copy(zinstream, writer, "UTF-8");
  String response = writer.toString();
  System.out.println(response);
  zentry = zinstream.getNextEntry();
}
于 2013-03-26T12:04:33.243 回答