简体   繁体   English

Java从jar中的资源重新加载文本文件

[英]Java reloading text file from resources within jar

I have a standart maven project: 我有一个标准的Maven项目:

src/

| --- main/*.java

| --- resources/

    |--- settings1.ini

    |--- settings2.ini

That's the way I am reading this settings files: 这就是我读取此设置文件的方式:

InputStream settingsFileInputStream = ClassLoader.getSystemResourceAsStream(this.configurationFileName);

All works fine but I have to provide functionality to reload these settings1.ini and settings2.ini files at runtime when I am running maven-compiled .jar file. 一切正常,但是当我运行maven编译的.jar文件时,我必须提供在运行时重新加载这些settings1.inisettings2.ini文件的功能。 How can I do this? 我怎样才能做到这一点?

Because as far as I know I can't access any data in .jar archive and modify it. 因为据我所知,我无法访问.jar存档中的任何数据并对其进行修改。

You can access a file in one of your application's JAR files (assuming it is on the classpath) using a stream opened using ClassLoader.getResourceAsStream(resourcePath) . 您可以使用使用ClassLoader.getResourceAsStream(resourcePath)打开的流来访问应用程序的JAR文件之一中的文件(假定它在类路径中ClassLoader.getResourceAsStream(resourcePath)

However, you cannot update a file in a JAR file. 但是,您无法更新JAR文件中的文件。 Or to be more accurate: 或更准确地说:

  • updating a JAR (using the Java SE libraries) entails rewriting it, 更新JAR(使用Java SE库)需要重写它,

  • there are many situations where a application won't be able to write to its JAR file, 许多情况下,应用程序将无法写入其JAR文件,

  • even if it can do it, the application may only see the results of the updates after it has been restarted, and 即使可以做到,应用程序也只能在重新启动后才能看到更新结果,并且

  • it is a bad idea for an application to update itself in this way for various reasons ... including security. 对于应用程序出于各种原因(包括安全性)以这种方式进行自我更新是一个坏主意。


If you want the file to be updateable, I suggest the following approach: 如果您希望文件可更新,我建议采用以下方法:

  1. Pick a standard location for the file on the user's machine; 为用户计算机上的文件选择一个标准位置; eg on Linux, you might pick a hidden subdirectory of the current user's home directory. 例如,在Linux上,您可以选择当前用户主目录的隐藏子目录。

  2. On starting the application, see if the file exists, and if it doesn't populate it from the copy in the JAR file. 启动应用程序时,请查看文件是否存在,以及是否不从JAR文件中的副本填充文件。

  3. When the application then needs to read or update the file, read or update it at the above location. 当应用程序随后需要读取或更新文件时,请在上述位置读取或更新文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM