1

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 ?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
dogfish
  • 2,646
  • 4
  • 21
  • 37
  • why didn't you post the stacktrace? – isnot2bad Nov 23 '13 at 21:25
  • 1
    A File represents a path on the file system. A file in a jar is not on the file system. So whatever the class from which you execute this code, it makes no sense, and won't work. To read a file inside a jar that is in the classpath, use `Class[Loader].getResourceAsStream()`. – JB Nizet Nov 23 '13 at 22:24
  • Seems to be the same as http://stackoverflow.com/questions/10144210/java-jar-file-use-resource-errors-uri-is-not-hierarchical – jCoder Nov 23 '13 at 22:25

1 Answers1

2

By the time of deployment, those resources will become an . 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.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433