0

我正在使用 ZipInputStream 读取 zip 文件。Zip 文件有 4 个 csv 文件。有些文件是完全写入的,有些是部分写入的。请帮助我找到以下代码的问题。从 ZipInputStream.read 方法读取缓冲区是否有任何限制?

val zis = new ZipInputStream(inputStream)
Stream.continually(zis.getNextEntry).takeWhile(_ != null).foreach { file =>
      if (!file.isDirectory && file.getName.endsWith(".csv")) {
        val buffer = new Array[Byte](file.getSize.toInt)
        zis.read(buffer)
        val fo = new FileOutputStream("c:\\temp\\input\\" + file.getName)
        fo.write(buffer)
 }
4

1 回答 1

0

您尚未close编辑flush您尝试写入的文件。它应该是这样的(假设 Scala 语法,或者这是 Kotlin/Ceylon?):

    val fo = new FileOutputStream("c:\\temp\\input\\" + file.getName)
    try {
      fo.write(buffer)
    } finally {
      fo.close
    }

此外,您应该检查读取计数并在必要时阅读更多内容,如下所示:

var readBytes = 0
while (readBytes < buffer.length) {
  val r = zis.read(buffer, readBytes, buffer.length - readBytes)
  r match {
    case -1 => throw new IllegalStateException("Read terminated before reading everything")
    case _ => readBytes += r
  }
}

PS:在您的示例中,它似乎少于所需的关闭}s。

于 2017-06-16T05:54:23.287 回答