Jonas Praem Jonas Praem -4 years ago 132
Groovy Question

GroovyCastException when calling java.util.zip.ZipFile.getInputStream()

I am trying to read a file from a jar archive, and return it as an java.io.InputStream.

Here is the method where I am trying to accomplish this:

InputStream getExportInfo(path) {
def zipFile = new java.util.zip.ZipFile(new File(path))

zipFile.entries().each { entry ->
def name = entry.name
if (!entry.directory && name == "ExportInfo") {
java.io.InputStream is = zipFile.getInputStream(entry)
return is
}
}
}


However I am getting this error from console:


org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'java.util.zip.ZipFile$ZipEntryIterator@49defb82' with class 'java.util.zip.ZipFile$ZipEntryIterator' to class 'java.io.InputStream'


It looks like the .getInputStream(entry) doesn't return a 'java.io.InputStream', but it should according to the documentation

Where does this 'cast' even come from ?

Answer Source

You are returning from the closure, which brings the cast exeption up when your call the method.

The easy fix would be to change the groovy iteration to plain for loop:

InputStream getExportInfo(path) {
  def zipFile = new java.util.zip.ZipFile(new File(path))

  for( ZipEntry entry in zipFile.entries() ){
    def name = entry.name
    if (!entry.directory && name == "ExportInfo") {
      return zipFile.getInputStream(entry)
    }
  }
}

then it would break the loop and return your inputStream instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download