How to read a file inside a jar's resources fr

2019-03-01 00:33发布

问题:

I have a file X.json inside abc.jar in its classpath. There is a method readFile in abc.jar which reads the file as

URL url = Abc.class.getClassLoader().getResource("X.json");  
File file = new File(url.toURI());*

which reads it fine if i run it from within the jar's context i.e main method in some file inside the abc.jar

But when readFile is called from from outside of abc.jar from some other code it fails with java.lang.IllegalArgumentException: URI is not hierarchical

How do I get the File object by calling the method readFile from outside the jar's context ?

回答1:

By the time of deployment, those resources will become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.