Mi W Mi W -4 years ago 43
Java Question

Replacing a .xml file within jar

I am trying to make changes to an xml file stored within a jar file in Java.

My program reads the xml file from the jar, makes a few changes to it using:

javax.xml.parsers.DocumentBuilder
javax.xml.parsers.DocumentBuilderFactory
org.w3c.dom.Document;


This works without any issues. I then write those changes to a new xml file using the following lines of code:



TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
DOMSource source = new DOMSource(doc);
File tempStorage = new File("/some/directory/config.xml");
StreamResult result = new StreamResult(tempStorage);
trans.transform(source, result);





Which works perfectly. After this, I add the xml file into the jar using the following console command:

jar uf jarFile.jar "/some/directory/name.xml"


This adds the xml file into the jar within the directory specified. I want to add it to the base directory of the jar. For example, when I unpack the jar I want the folder structure to be this:

jarFolder/config.xml


NOT

jarFolder/some/directory/config.xml


Replacing the temp storage directory with just "config.xml" does not work, as I am running the program through eclipse, and it stores the file as:

jarFolder/eclipse/directory/eclipse.app


Ideally I want to keep the config file within the jar so I don't have a bunch of loose files associated with my program, and can simply read config.xml without having to check for loose files created from running the program previously. I should also mention that config.xml is already stored in the jar to begin with.

Answer Source

Try mentioning the directory as below. The -C option helps you specify the target directory where you want the file.

jar uf jarFile.jar -C . "/some/directory/name.xml"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download