Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing XML in Java FileNotFoundException

Tags:

java

xml

i am facing some problem for this following codes

       try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            //root elements
            Document doc = docBuilder.newDocument();

            Element rootElement = doc.createElement("subcompany");
            doc.appendChild(rootElement);

            //id elements
            Element id = doc.createElement("id");
            id.appendChild(doc.createTextNode(subCompanyId != null ? subCompanyId : " "));
            rootElement.appendChild(id);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            String xmlPath = "/project/MallDirectory/mall";

            //EDITED for File creation before writing.
            boolean isFileCreated = new File(xmlPath, "subcompany.xml").createNewFile();
            System.out.println(isFileCreated);                

            StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));

            transformer.transform(source, result);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

After i run, i get this following error:

javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)

It used to work on my other project, however not this time round. What exactly went wrong here ?

EDITED:

Here is the path that i am trying to write into. The file is created, but it is empty.

enter image description here

like image 420
Charlie Kee Avatar asked Mar 10 '13 15:03

Charlie Kee


1 Answers

I managed to solve the problem.

Here is the Error:

javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)

I am thinking maybe the transformer is trying to write the xml to this path 'file:/project/MallDirectory/mall/subcompany.xml'. I don't know how it happened, as i have specifically set the file path '/project/MallDirectory/mall/subcompany.xml', and does not prefixed with 'file:/'.

Therefore, i somehow managed to fix it by doing this:

...

//ERROR CODE:
//StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));
//
StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml").getPath());
transformer.transform(source, result);

...
like image 125
Charlie Kee Avatar answered Oct 02 '22 00:10

Charlie Kee