0

I have a piece of code that is meant to update an xml file that is inside the package and in a resource folder (This is a standalone desktop project). This code runs well in the IDE when I include the path to the src folder eg

File file = new File("src/tools/con.xml");

My problem is that this doesn't work outside of the IDE for example in a deployed application because the resource is bundled into a jar. I have tried using classloader methods getResource/getResourceAsStream() but without success e.g.

File file = new File(getClass().getResource("/tools/con.xml").toString() );

Below is my full code

try{
    File file = new File("src/tools/con.xml");

    StreamResult result = new StreamResult(file); 
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    DOMSource source = new DOMSource(doc);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(source, result);

}catch (IllegalArgumentException | TransformerException e) { 
    throw new IOException("Failed to save the doc");
}
Tovs
  • 157
  • 2
  • 13
  • 3
    You should not try to update a resource file bundled with the Jar in runtime. The Xml file you're trying to update should be an external resource (by external, I mean it must reside outside of the Jar file). – Martín Zaragoza Aug 13 '18 at 18:08
  • 1
    That makes sense, I just wanted to package the project as a single file. I will explore your suggestion. – Tovs Aug 13 '18 at 18:17
  • 1
    You can package the project as a single file, but as soon as the user wants to change something, you'll need to write out the *new* stuff, either in toto, or as a diff, to something external. – Dave Newton Aug 13 '18 at 18:38

1 Answers1

2

I am afraid that the only possibility is to unbundle the jar, add your xml and rebundle it. I had to do the same with a pom.xml for a war file but I believe the procedure will be the same.

yohann
  • 36
  • 3