Loading and saving resources inside a runnable jar? [duplicate]

拈花ヽ惹草 提交于 2019-12-07 20:44:28
trashgod

How about you write settings to a well known location outside of the JAR?

As alternatives for saving settings, consider one of these approaches:

  • java.util.prefs.Preferences, mentioned here.

  • JWS PersistenceService, described here.

  • Cookies, discussed in Accessing Cookies.

For others who come across this question.

You cannot do this unless you can place constraints on the OS being used, and even then you may not be able to do this.

Here are some constraints to be aware of:

  • Microsoft Windows implements its own read-write lock symmantics: you cannot write to a file while there is a read handle open. The JVM will have a read handle open as the this is the file on the classpath, therefore not possible in Java (unless you want to fork a temporary process, kill yourself, let the temp process rewrite and relaunch... Which will be ugly and the anti-virus will likely stop the temp process anyway)

  • Most unix OS implementations will have no issue, though the JVM will have cached offsets within the JAR file, so your program will crash as soon as you are done and attempt to load a class.

  • only windows users tend not to use file permissions to lock down write access to executables, so it is invalid to assume you have write access on the jar.

The second point has you dead in the water for all OS impls (unless you can live with a fork, and the fork makes a lot of risky assumptions anyway)

Just write to a separate file and be done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!