Search code examples
scalazipinputstream

ZipInputStream.read in ZipEntry


I am reading zip file using ZipInputStream. Zip file has 4 csv files. Some files are written completely, some are written partially. Please help me find the issue with below code. Is there any limit on reading buffer from ZipInputStream.read method?

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)
 }

Solution

  • You have not closed/flushed the files you attempted to write. It should be something like this (assuming Scala syntax, or is this Kotlin/Ceylon?):

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

    Also you should check the read count and read more if necessary, something like this:

    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: In your example it seems to be less than required closing }s.