Lyubov Alekseeva
Lyubov Alekseeva

Reputation: 209

getResourceAsStream path related to project stucture?

I know this should be simple, but surprisingly I can't google an answer.

I have this structure :

Myproj

|-src

|--com.mypackagename

|---MyClass.java

|-xml

|--book.xml

XMLInputFactory factory = XMLInputFactory.newInstance();
ClassLoader cl = MyClass.class.getClassLoader();
XMLStreamReader reader = factory.createXMLStreamReader(cl.getResourceAsStream("xml/book.xml"));

and it doesn't find my xml. Obviously, the path is wrong. Please, help me - how shall i set it right

Upvotes: 0

Views: 239

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347204

Assuming that the xml directory is not within the classpath context of your application (ie embedded within the application Jar or with the classpath property), then you will need to reference the XML file as a File. The path to which will be relative to the execution location of the program.

If the xml directory is within the classpath context (ie classpath=.\xml;...), then you will need to use a path something like /book.xml.

If the xml directory is relative to the classpath context (ie classpath=.;...), then you will need to use a path something like /xm/book.xml.

If the xml directory is embedded within the application context (packaged within the Jar), then you will need use either /book.xml or /xml/book.xml depending on how the directory is packaged

Upvotes: 0

Viswanath Donthi
Viswanath Donthi

Reputation: 1821

The problem is that getResourceAsStream() will only load resources from the classpath. And as per given directory your xml file is not located on classpath. So, place your xml file under WEB-INF/classes/book.xml and access it as:

getResourceAsStream("book.xml")

Upvotes: 1

Shirish Bari
Shirish Bari

Reputation: 2722

If you book.xml file is kept in class path then you can simply access it by writing cl.getResourceAsStream("book.xml").

Upvotes: 0

Related Questions