0
votes

I am working with Intellij and my XML file is in the below path -

C:\workspace\one\two\three\src\main\java\com\package\serv\ap\versionOne\fine.xsd

Now I am trying to read this XML file as I need to make StreamSource object from it. When I use absolute path, then it works fine -

StreamSource XSD = new StreamSource(new File("C:\\workspace\\one\\two\\three\\src\\main\\java\\com\\package\\serv\\ap\\versionOne\\fine.xsd"));

But the above is not the right way to do it as it will not work in other machines. So I tried using getResourceAsStream but that doesn't work for me as I get everything as null inside StreamSource object

StreamSource XSD = new StreamSource(this.getClass().getResourceAsStream("fine.xsd"));

Is there anything wrong I am doing while trying to load xml file?

3
What are you trying to achieve?SimY4
@SimY4 I am just trying to find a way to read the XML file using the right way not with the absolute path since it won't work in other machines. I am not sure how would I do that.john

3 Answers

1
votes

You need to get your xsd file on the classpath. Then you will be be able to read the file the same way regardless whether you are in IntelliJ or running somewhere else.

In IntelliJ add the folder to the project classpath the same way you would for a jar file.

When you build a jar file to run your application elsewhere include the xsd in the root of the jar file.

Then you can use getResourceAsStream() no matter where your application is running from.

0
votes

There are Classes like DocumentBuilderFactory which enables applications to obtain a parser that produces DOM object trees from XML documents & & DocumentBuilder used to obtain DOM Document instances from an XML document. DocumentBuilderFactory - JDK API & DocumentBuilder - JDK API.

For demo example : How To Read XML File In Java – (DOM Parser)

-2
votes

Use

System.getProperty("user.dir");

This will give you the pwd and you can navigate from there.