6

Here's my structure:

  • com/mycompany/ValueReader.class
  • com/mycompany/resources/values.xml

I can read the file in my Eclipse project, but when I export it to a .jar it can never find the values.xml.

I tried using ValueReader.class.getResource() and ValueReader.class.getResourceAsStream() but it doesn't work.

What's the problem here? How do I get a File-object to my values.xml?

B.

B. T.
  • 111
  • 1
  • 2
  • 5
  • possible duplicate of http://stackoverflow.com/questions/2504272/shipping-java-code-with-data-baked-into-the-jar – Kris Mar 31 '10 at 12:46

4 Answers4

8

You can't get a File object (since it's no longer a file once it's in the .jar), but you should be able to get it as a stream via getResourceAsStream(path);, where path is the complete path to your class.

e.g.

/com/mycompany/resources/values.xml
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • I tried it and it didn't work. Your approach was correct tho. I used getResourceAsStream(path), but instead of path=com/mycompany/resources/values.xml, i used path=resources/values.xml and it's working. Thanks anyway! – B. T. Mar 31 '10 at 12:32
  • 4
    it hasn't worked because you didn't put the leading slash, which means the root of the classpath. Without it the path is relative. – Bozho Mar 31 '10 at 12:58
  • Ah true. Thanks. I'll never forget this anymore! – B. T. Mar 31 '10 at 13:07
2

You can't get a File for the file because it's in a jar file. But you can get an input stream:

InputStream in = ValueReader.class.getResourceAsStream("resources/values.xml");

getResourceAsStream and getResource convert the package of the class to a file path, then add on the argument. This will give a stream for the file at path /com/mycompany/resources/values.xml.

tbodt
  • 16,609
  • 6
  • 58
  • 83
0

This will work...

Thread.currentThread().getContextClassLoader().getResource("com/mycompany/resources/values.xml")
demongolem
  • 9,474
  • 36
  • 90
  • 105
-1

You can extract the jar then take what you want, in the same class-path using :

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new   
FileInputStream(zipfile.getCanonicalFile())));
NoNaMe
  • 6,020
  • 30
  • 82
  • 110
WALID
  • 1