Beginner Question: How to access an XML file inside a JAR without extracting it

S

SK

Hi,

I am using JDOM to parse the XML files. I have a file inside a JAR
file that I want to read but without extracting it from the JAR
itself. Can anyone send me some code which does it.

Thanks for the help in advance.
- SK.
 
M

Mike

(e-mail address removed) (SK) wrote in message
The idea is that if the class (the code) was able to be loaded from
the jar file, then you ought to be able to ask that same classloader
that loaded the class to load something else for you. Like so:

InputStream is = getClass().getClassLoader().getResourceAsStream("something.xml");

Now you have an input stream. I'm sure there are a few API's
available that can then load the DOM from the input stream. In fact,
I'm doing it using JDOM all the time. JDOM rocks.
 
A

Anthony Borla

SK said:
Hi,

I am using JDOM to parse the XML files. I have a
file inside a JAR file that I want to read but without
extracting it from the JAR itself. Can anyone send me
some code which does it.

Use:

* Class.getResourceAsStream to extract your XML file
as a byte sequence from the JAR

* Parse using the appropriate method which accepts an
'InputStream' as argument i.e.

DocumentBuilder db =
DocumentBuilderFactory.newDocumentBuilder();

db.parse(theInputStream);

Whenever accessing a JAR you are always *extracting* data. Indeed, the
essence of a 'read' task is extraction. Even using the 'jar' utitlity to
list JAR file contents sees a sequence of bytes 'extracted' in order to
obtain the relevant data. The difference is, however, whether that data is
immediately 'consumed' by the program [as would be the case when parsing an
XML document stored in a JAR], or perhaps used to create other entities like
files.

I hope this helps.

Anthony Borla
 
C

Chris

The XML file is in the classpath of your app as its part of the JAR,
so you can use Class.getResourceAsStream to get an input-stream to it,
which you can then pass into the SAX builder.

- sarge
 
Joined
Sep 19, 2009
Messages
1
Reaction score
0
The code works

I tried the code suggested in this thread and it works perfectly. I can run a Java application from a jar file and access a XML file archived within the jar. It surprises me that an object of an abstract class, InputStream, can be set up this way. The getClass() method returns a class object, in this case, the input stream representing the archived XML file. Is this just a reference to the input stream? How can this work?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top