I have a java app, that needs to save and load user settings. I want to save them in a file located in the JAR file, how could I achieve this?
问题:
回答1:
That's not possible. Rather consider using java.util.prefs.Preferences
which is designed for exactly this purpose. See also this little guide.
回答2:
This is not a sensible course of action.
A JAR file is basically just a ZIP file. To rewrite its contents you need to extract them in full, make changes as needed and then write them to a new file that replaces the old one.
If the program that is going to do this is the same one as that contained in the JAR file, this becomes impossible as the file is write protected during execution.
You'd be better advised to store your configuration elsewhere.
回答3:
That is not the way to store preferences as others said.
If you has to do it that way then :
Locate the JAR from code: How to get the path of a running JAR file?
Unjar the contents to temp folder
Modify in the temp folder
Jar temp folder to the new JAR file.
回答4:
To add to what Kris said, most security experts will tell you that it's generally a bad security practice to allow end-user applications to modify their own code. What you're asking for would require that.