It's not a secret anymore!
The moose likes Beginning Java and the fly likes Placing XML on the classpath Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Placing XML on the classpath" Watch "Placing XML on the classpath" New topic

Placing XML on the classpath

Prash Singh
Ranch Hand

Joined: Aug 23, 2009
Posts: 103

Dear All,

I am having a problem dealing with this issue, Don't know whether it is feasible or not.
The situation is , I have a jar that reads a specific xml file from the class path using the following code.

The jar which I have developed will be used in multiple environments like servlets , swing etc.

The restriction I have here is that the "TO_BE_READ.xml" file has to be in a jar or to be placed along with the class that reads it.

My question is , Is it possible to place that xml file separate from the classes.
Like, if I am putting jar on class path of an application, then is it possible for the jar to locate and read the xml file with in the application.


Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4642

Jars don't locate anything. They're just hunks of data. You're also mixing up references to two different Jars: The Jar you're developing and one that contains the XML file. Please be more clear in which you are referring to, when you explain your requirements.

Now, what I understand what you want to do is read a file that's stored in a Jar file, which is on the classpath.

If you know that the file will always be bundled together with a specific (related) class, you can invoke getResourceAsStream() on the class literal (e.g. MyClass.class.getResourceAsStream("/directory/file.xml");).

If the xml file has no related class, then you can use the system class loader to get the resource: ClassLoader.getSystemResourceAsStream().

A third and more troublesome way is to handle the Jar file directly, using the java.util.jar.JarFile class.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: Placing XML on the classpath
It's not a secret anymore!