Reputation: 43
I am trying to creating an XML file using java. I am explicitly passing the path for the new XML file to be created and it is getting created successfully. But now, how do I get the XML file in the project folder automatically without giving the path.
My CWD is - C:\Users\sit\eclipse-workspace\XMLProject\src
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\Users\sit\eclipse-workspace\XMLProject\src\abc.xml"));
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
Upvotes: 0
Views: 79
Reputation: 5859
StreamResult result = new StreamResult(new File("abc.xml"));
Simply just give it the file name without the absolute path and it will put it in the project folder. If you want it specifically in the src folder, then you need to:
StreamResult result = new StreamResult(new File("src\\abc.xml"));
Instead of an absolute path, we are giving it a relative path. Take a look here for better understanding how to use paths and differences between them.
Upvotes: 2