Open and edit file in .jar with Java?

2019-05-01 12:23发布

How would you go about opening an .xml file that is within a .jar and edit it?

I know that you can do...

InputStream myStream = this.getClass().getResourceAsStream("xmlData.xml");

But how would you open the xmlData.xml, edit the file, and save it in the .jar? I would find this useful to know and don't want to edit a file outside of the .jar... and the application needs to stay running the entire time!

Thank you!

2条回答
孤傲高冷的网名
2楼-- · 2019-05-01 12:48

If you app. has a GUI and you have access to a web site/server, JWS might be the answer. The JNLP API that is available to JWS apps. provides services such as the PersistenceService. Here is a small demo. of the PersistenceService.

The idea would be to check for the XML in the JWS persistence store. If it is not there, write it there, otherwise use the cached version. If it changes, write a new version to the store.

The demo. writes to the store at shut-down, and reads at start-up. But there is no reason it could not be called by a menu item, timer etc.

查看更多
手持菜刀,她持情操
3楼-- · 2019-05-01 13:03

Jar files are just .zip files with different file suffix, and naming convention for contents. So use classes from under java.util.zip to read and/or write contents.

Modifying contents is not guaranteed (or even likely) to effect running system, as class loader may cache contents as it sees fit.

So it might be good to know more about what you are actually trying to achieve with this. Modifying contents of a jar on-the-fly sounds like complicated and error-prone approach...

查看更多
登录 后发表回答