在运行时更新资源文件 [英] Updating resource files at runtime

查看:53
本文介绍了在运行时更新资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序启动时,它使用以下代码读取配置属性文件:

When my application starts it reads a configuration properties file using the following code:

        Properties properties = new Properties();

        // parse the config resource

        try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename))
        {
            if (input == null)
            {
                // throw exception
            }

            // read the property list (key-value pairs) from the input byte stream
            properties.load(input);
        }

我能够读取和设置各个属性.

I am able to read and set individual properties.

属性文件位于 src/main/resources 中,在我使用maven构建应用程序之后,将其副本放置在 target/classes 中.当我打开它时,创建的jar文件在根目录中也有一个副本.

The properties file is located in src/main/resources and after I build the application using maven, a copy of it is placed in target/classes. The jar file that is created also has a copy of it in the root directory when I open it up.

我还希望能够覆盖属性文件,以便下次应用程序启动时,它将读取新的更新文件.我该如何实现?可能吗?

I would also like to be able to overwrite the properties file so that next time the application starts up, then it will read the new updated file. How do I achieve this? Is it even possible?

我发现了这个问题,但没有答案.

I found this question but no answers.

我已经尝试过了:

        try (OutputStream output = new FileOutputStream(filename))
        {
            properties.store(output, null);
        }

如果我只想完全创建一个新文件,则可以使用.然后,我将不得不修改应用程序,以便它从给定的文件夹中读取,而不是从资源文件夹中读取.这是我应该做的吗?

which works if I just want to create a new file altogether. I would then have to modify the application so that it reads from a given folder rather than what originated from the resources folder. Is this what I should be doing?

我对Java还是很陌生,所以请放轻松.

I'm fairly new to Java so please go easy.

推荐答案

在资源允许的情况下,将初始默认值属性存储在jar文件中.

Storing the initial, default properties in the jar file, as resources is fine.

但是,如果您希望它们可写,则需要将它们作为文件真正存储在磁盘上的某个位置.通常,在用户主目录中的 .yourapp 目录下(或 .yourapp 文件中).

But if you want them to be writable, then you need to really store them as a file somewhere on the disk. Typically, under a .yourapp directory (or in a .yourapp file) inside the user's home directory.

因此,请尝试查找该文件,如果不存在,则回退到资源.写入时,请始终写入文件.

So, try finding the file, and if not present, fallback to the resources. When writing, always write to the file.

这篇关于在运行时更新资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆