Accessing a resource within a jar (working in Netb

2019-02-27 17:30发布

问题:

I have a jar file with bundled resources (language model binary files) that need loading at run time. The directory structure within the jar is

tagger/app.class
tagger/models/stop/SentDetect.bin.gz

where SentDetect.bin.gz is a binary whos path is loaded into a thirdparty class (SentDetector) as a String parameter, i.e.

URL url = this.getClass().getResource("models/stop/SentDetect.bin.gz");
SentenceDetector sdetector = new SentenceDetector(url.getPath());

While it runs ok in Netbeans, when I try to run it as a jar from command line, I get a FileNotFound Exception at the constructor. I have double checked that the binary is included in the compiled Jar file.

I believe the solution would usually be to load the data in as an input stream using getResourceAsStream(), but this is not an option here, as the url is being passed as a String parameter to a third party constructor, which leads me to believe the problem is with how the url is being parsed to a String?

I have tried:

url.getPath();
url.getFile();
url.toURI().getPath();
url.toString();

and all are giving different paths to the file.

回答1:

It sounds like that should be fine, if the binary is definitely in the right place and the jar file is definitely in the class path. (I assume it can find the class itself? I'd expect so, given that you're using this.getClass()).

One thing which might be causing issues is filename casing - when it's loading the file from the file system, if you're using Windows that'll be case insensitive; in a jar file it'll be case sensitive. Check the case in code matches the case in the jar file.



回答2:

You can't access a resource in a Jar file via java.io.File. You should provide an alternate constructor for SentenceDetector which either accepts an InputStream rather than a String, or which accepts an URL and uses URL.openStream() to get an InputStream.