20
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("com/x/y/z.cfg");
File file = new File(url.getPath());

This works when running jar file from Eclipse but not works when running in a jar file.

java.io.FileNotFoundException: file:\C:\Users\nova\Desktop\Matcher.jar!\c om\x\y\z.cfg

This is not a duplicate. I've checked all other questions, no useful information.

ifloop
  • 8,079
  • 2
  • 26
  • 35
Insignificant Person
  • 863
  • 2
  • 10
  • 24
  • 1
    What do you want to do with that `File` once you've got it? You can't create a `File` from the `URL` you get for a resource in a JAR (because it's not a `file:` URL, it's typically `jar:file:/path/to/file.jar!/com/x/y/z.cfg`), but if the API you're using can accept a `URL` or an `InputStream` instead of a `File` then you don't need to. – Ian Roberts Oct 31 '14 at 12:55
  • 8
    This is explained many times: [here](http://stackoverflow.com/questions/944610/how-do-i-access-a-config-file-inside-the-jar), [here](http://stackoverflow.com/questions/20389255/java-reading-a-resource-file-from-within-jar), [here](http://stackoverflow.com/questions/403256/how-do-i-read-a-resource-file-from-a-java-jar-file?rq=1). The reson is really because File represents a file system object and contents of jar are not accessible by file system (but Java can handle it in some way - as an InputStream). – Stanislav Lukyanov Oct 31 '14 at 12:59
  • URL.getFile() *does not* convert a URL into a valid file path. It merely returns the path portion of the URL. (In the days of Java 1.0, most URLs referred to physical files; that is why the method is named getFile.) – VGR Mar 01 '17 at 16:41

2 Answers2

36

When file is bundled inside the jar then it become byte stream instead of a normal File object.

Try

InputStream stram=getClass().getClassLoader().getResourceAsStream(relativePath);

More Tutorial...

Read similar post here and here

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
2

You can't create a File instance, because the only file you have is the JAR. That's why getResource() returns URL. You can get stream by using URL.openStream() method to read contents.

McMonster
  • 171
  • 1
  • 10