将一些内容保存到 JAR 中
我有一个java应用程序,需要保存和加载用户设置。我想将它们保存在 JAR 文件中的一个文件中,如何实现这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那是不可能的。而是考虑使用
java.util.prefs .Preferences
正是为此目的而设计的。另请参阅这个小指南。That's not possible. Rather consider using
java.util.prefs.Preferences
which is designed for exactly this purpose. See also this little guide.这不是明智的做法。
JAR 文件基本上就是一个 ZIP 文件。要重写其内容,您需要完整提取它们,根据需要进行更改,然后将它们写入一个新文件来替换旧文件。
如果要执行此操作的程序与 JAR 文件中包含的程序相同,则这是不可能的,因为该文件在执行期间受到写保护。
最好将您的配置存储在其他地方。
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.
这并不是像其他人所说的那样存储偏好的方式。
如果您必须这样做,那么:
从代码中找到 JAR:如何获取正在运行的 JAR 文件的路径?
将内容解压到临时 文件文件夹
在临时文件夹中修改
将临时文件夹Jar 到新的JAR 文件。
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.
补充一下 Kris 所说的,大多数安全专家会告诉您,允许最终用户应用程序修改自己的代码通常是一种不好的安全做法。你所要求的就需要这样。
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.