This is probably something incredibly dumb on my part, but I’ve been fighting with it for an hour.
Given these classes, all in the same package:
- ParsingClass.java
- CatalogHandler.java (extends DefaultHandler, adds a ConfigMap field)
- hd.xml
Since the class and the XML are in the same package, I didn’t expect to have to fight to find the XML file. Unfortunately, the best laid plans often go awry.
private static Map<String, Object> parseCatalogXml(String catalogName) {
SAXParserFactory factory = SAXParserFactory.newInstance();
CatalogHandler handler = new CatalogHandler();
try {
SAXParser parser = factory.newSAXParser();
File file = new File(catalogName + ".xml");
if (!file.exists()) {
throw new IllegalStateException("Unable to find file: " + file.getName());
}
parser.parse(file, handler);
} catch (SAXException ex) {
} catch (ParserConfigurationException ex) {
} catch (IOException ex) {
}
return handler.getConfigMap();
}
Using new File(“”).getAbsolutePath() didn’t work from either the IDE or using maven on the command line.
I think this is a classpath/working directory issue @Jason. Even though your file is “all in the same package”, that doesn’t mean that Java is running in that directory.
What you most likely need to do is move the XML file to another “source folder” (Eclipse language). In my projects I have my source in:
and my XML and other config files in:
Then you can find the XML files in the top of the classpath with something like: