Need help with strange Class#getResource() issue

前端 未结 4 1791
太阳男子
太阳男子 2021-01-20 01:26

I have some legacy code that reads a configuration file from an existing jar, like:

URL url = SomeClass.class.getResource(\"/configuration.properties\");
//          


        
相关标签:
4条回答
  • 2021-01-20 02:01

    There are bugs in several Java versions when using file URLs containing spaces. "/path/to/jar" is probably not your real path, so I at least assume that this is what you're running into. Your code is at least in theory ok.

    0 讨论(0)
  • 2021-01-20 02:13

    A typical implementation of ClassLoader.getResourceAsStream is:

    public InputStream getResourceAsStream(String name) {
        URL url = getResource(name);
        try {
            return url != null ? url.openStream() : null;
        } catch (IOException e) {
            return null;
        }
    }
    

    Class.getResource and getResourceAsStream behave the same as each other.

    So it looks like either you are using a strange and broken subclass of ClassLoader, or there is some mistake in the tests on your side.

    0 讨论(0)
  • 2021-01-20 02:13

    It works with getresourceasstream because it is in the classpath, but it doesn't work with the URL maybe because the URL is not ok.

    I don't know if the URL that getResource is creating is not ok, or there isn't a correct handler for the protocol (wouldn't it be file:jar:c:/myjar.jar!configuration.properties or something by the like (with two colons?)

    0 讨论(0)
  • 2021-01-20 02:22

    use urlConnection.setUseCaches(false), since it's an ant task, it's likely not to be forked in a separate process. The URLs cache the files (or the JarFile in that case)... if the files is change due to the build, you get quite a similar behavior.

    you may want to close the modified jar files meanwhile useCaches(true), JarURLConnection.getJarFile().close()

    Sometime I wish handling of Jar/Zip was a little better

    cheers

    0 讨论(0)
提交回复
热议问题