0

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();
          }
        }
    }

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.