无效的文字/长度代码 - 如何解决这个问题?

时间:2013-05-22 11:24:14

标签: groovy gradle

我是groovy的新手,我想从jar文件中解压缩资源。我以这种方式试了一下,因为tim_yates在这里写了https://stackoverflow.com/a/16645378/2069368

getClass().getResource('/resources/my.dll').withInputStream {
    is -> new File("my.dll").withOutputStream {
        os -> os << is
    }
}

但我收到错误:

Caused by: java.util.zip.ZipException: invalid literal/length code
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
    at java.io.FilterInputStream.read(FilterInputStream.java:133)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.leftShift(DefaultGroovyMethods.java:9643)
    at org.codehaus.groovy.runtime.dgm$458.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)

我也试过这个:

getClass().getResource('/resources/my.dll').withInputStream {
    is -> new File("my.dll").withOutputStream {
        os -> Files.copy(is, os)
    }
}

但没有成功。我检查过is是否可用且是(is.available()返回914432)

[编辑]

如果我尝试以这种方式复制文件,它可以工作:

new File("C:\\Document.html").withInputStream {
    is -> new File("C:\\Document_Copy.html").withOutputStream {
        os -> os << is
    }
}

我确信my.dll在jar文件中 - 我从本地maven存储库加载jar。有什么想法吗?

[另一个编辑]

我已将新文件plik.txt添加到资源目录。运行应用程序后,我收到错误JAR entry resources/plik.txt not found in C:\Users\uer\.m2\repository\pl\gradle\is2k8\0.9\is2k8-0.9.jar。我不知道为什么会出现这个错误。我检查了它,并且jar文件中存在plik.txt。我还输入了非现有路径,例如getClass().getResources("/resources/thisdoesntexist.txt"),我收到此错误Cannot invoke method withInputStream() on null object

1 个答案:

答案 0 :(得分:0)

您应该始终使用getResourceAsStream来读取资源文件的内容,即使在Groovy中也是如此。如果资源路径(在Jar内)是resources/my.dll,并且Jar在类路径上,那么这应该有效:

def stream = getClass().classLoader.getResourceAsStream("resources/my.dll")
def file = new File("my.dll")
file.delete()
stream.withStream {
    file << stream
}