问题
I'm using configuration JSON file stored in src/test/resources/config.json
.
I'm getting it like this:
String configFile = this.getClass().getResources("config.json").getPath();
I have getPath()
method, because I need its String
value, then check if file exists and finally parse it.
In Eclipse IDE everything works fine, because I parse file /bin/config/config.json
, but when I create JAR file, the path is program.jar!/config/config.json
and function !Files.exists()
returns false.
How can i resolve this issue?
回答1:
Instead of referencing the file by it's path, when you use the resources loader you should open the file's InputStream.
Instead of .getResources("config.json").getPath();
Try using this.getClass().getResourceAsStream("config.json");
If the stream that is returned is null then the resource does not exist.
This way even if the resource is packed into a jar, the classloader will always return you the correct thing.
回答2:
You can't access a path inside a jar using the File
-class, since it's not a native file-system resource and reading from a jar requires a lot more than reading an ordinary file (unpacking etc).
So to load a file from a jar the best way you can go is using a classloader: it knows how to search jar-files, how to unpack them etc.
So to read the file you better use
InputStream configStream = this.getClass().getResourceAsStream("config.json");
You'll know the file doesn't exist on your classpath when configStream
is null
.
The only thing that's missing now is the String
-representation of the path, but I can't think of a usecase where you'd actually need it - and if you really, really need it you can use your old way to get it.
P.S.: I also can't think of a reason why you would have to check if the file exists when you got the path - if the file didn't exist this.getClass().getResources("config.json").getPath();
should fail with a NullPointerException
!!
回答3:
I think if you are using mvn to build the jar
you can build the jar with all the dependency. This will pack the dependent jars and files needed. You can read http://maven.apache.org/plugins/maven-assembly-plugin/descriptor-refs.html
in gradle https://github.com/musketyr/gradle-fatjar-plugin
来源:https://stackoverflow.com/questions/25362943/cant-load-resources-file-from-jar