getResourceAsStream() doesn't see resource

2019-02-26 00:14发布

问题:

I want to unpack resources from my jar file. The structure of jar looks like this:

my.jar
    META-INF
    resources
        my.exe
        my.dll
    my
        namespace
            UnpackResourceFromThisClass.class

I want to unpack my.exe and my.dll from jar file. I tried to unpack those files using this code:

try {
    InputStream is = getClass().getResourceAsStream("/resources/my.exe")
    OutputStream os = new FileOutputStream(new File(destDir))
    Files.copy(is, os)
    os.close()
    is.close()
}
catch (NullPointerException e) {
    e.printStackTrace();
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
catch (SecurityException e) {
    e.printStackTrace();
}

but it doesn't work. Any ideas? As a result I get this error:

java.lang.NullPointerException
    at java.nio.file.Files.provider(Files.java:65)
    at java.nio.file.Files.newInputStream(Files.java:106)
    at java.nio.file.Files.copy(Files.java:2884)
    at java_nio_file_Files$copy.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
    at pl.ydp.gradle.Is2k8Task.getResources(Is2k8Task.groovy:84)
    at pl.ydp.gradle.Is2k8Task.build(Is2k8Task.groovy:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1047)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:877)
    at org.gradle.api.internal.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:216)

This is groovy code which will be used in gradle custom task.

回答1:

You seem to be writing Java... Not sure if this will get you round your problem, but the above could be written in Groovy as:

this.getClass().getResource( '/resources/my.exe' ).withInputStream { ris ->
  new File( destDir ).withOutputStream { fos ->
    fos << ris
  }
}


回答2:

Delete the leading slash, getResourceAsStream will use the absolute path if the first character is a slash.



标签: groovy gradle