Reputation: 2126
I have the following code to open up an XML file for parsing. My problem is with the variable designPath
: it currently has to be a relative path from my program's root directory. However, when I pass an absolute path it doesn't work.
// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
// Load and Parse the XML document
// document contains the complete XML as a Tree
Document document = builder.parse(ClassLoader.getSystemResourceAsStream(designPath));
How can I make this work with either an absolute or relative path in the designPath
variable?
The issue is with the function ClassLoader.getSystemResourceAsStream
that takes a "resource of the specified name from the search path used to load classes." according to Java docs but I want to be able to use it with an absolute path.
Note that my designPath
may be on a different drive than my program.
Upvotes: 0
Views: 2649
Reputation: 911
Pass in an InputStream
instead:
// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
// Load and Parse the XML document
// document contains the complete XML as a Tree
File file = new File(PATH_TO_FILE);
InputStream inputStream = new FileInputStream(file);
Document document = builder.parse(inputStream);
or simple pass a new File
object
// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
// Load and Parse the XML document
// document contains the complete XML as a Tree
Document document = builder.parse(new File(PATH_TO_FILE));
Upvotes: 1
Reputation: 850
Well you can't because as you mentioned, getSystemResourceAsStream only searches the classpath.
You may have to so something like this.
Document document = null;
if (ClassLoader.getSystemResource(designPath) != null)
{
document = builder.parse(ClassLoader.getSystemResourceAsStream(designPath));
}
else
{
// use standard file loader
document = builder.parse(new File(designPath));
}
Swap the if clauses around if you want the file on the file system to take precedence.
Upvotes: 0