0

What you have asked is just writing and reading into a file as standalone java class. but it you go for a project like spring-mvc i cannot write or update the value.

I used File sequenceStorageFile = ResourceUtils.getFile("classpath:sequenceValue/sequence.xml"); to read data from this xml file. But I don't know how to write into the same file to update the value.

Can someone tell me how to write into the same xml file?

  • 1
    Possible duplicate of [How do I create a file and write to it in Java?](https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java) – M. Prokhorov Sep 28 '17 at 18:21

2 Answers2

0

Check below sample

 try {
        String filepath = "c:\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);
        node = doc.getFirstChild();
        Node nodecon = doc.getElementsByTagName("TAGNAME").item(0);

        NamedNodeMap attr = nodecon.getAttributes();
        Node nodeAttr = attr.getNamedItem("ID");
        nodeAttr.setTextContent("2");

        Element age = doc.createElement("ATTRIBUTE_NAME");
        age.appendChild(doc.createTextNode("NEW_ATTRIBUTE_VALUE"));
        nodecon.appendChild(age);

        NodeList list = nodecon.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
           Node node = list.item(i);
           if ("UPDATE_NODE_NAME".equals(node.getNodeName())) {
            node.setTextContent("NEW_NODE_VALUE");
           }
        }
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);



       } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
       } catch (TransformerException tfe) {
        tfe.printStackTrace();
       } catch (IOException ioe) {
        ioe.printStackTrace();
       } catch (SAXException sae) {
        sae.printStackTrace();
       }
0

Should not be done, one could use a resource "file" as a read-only template (it is possibly inside a sealed jar) to create a file, for instance in System.getProperty("user.home") directory.

InputStream in = getClass().getResourceAsStream("/sequenceValue/sequence.xml");
Path seqPath = Paths.get(System.getProperty("user.home"), "seq.xml");
Files.copy(in, path);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138