Java 在运行时更新资源文件
当我的应用程序启动时,它使用以下代码读取配置属性文件:Java 在运行时更新资源文件,java,maven,properties,resources,Java,Maven,Properties,Resources,当我的应用程序启动时,它使用以下代码读取配置属性文件: Properties properties = new Properties(); // parse the config resource try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename)) { if (input == null)
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);
}
我能够读取和设置单个属性
属性文件位于src/main/resources中,在我使用maven构建应用程序之后,它的一个副本被放置在target/classes中。当我打开创建的jar文件时,它在根目录中也有一个副本
我还希望能够覆盖属性文件,以便下次应用程序启动时,它将读取新的更新文件。我如何做到这一点?有可能吗
我发现了问题,但没有答案
我试过这个:
try (OutputStream output = new FileOutputStream(filename))
{
properties.store(output, null);
}
如果我只想创建一个新的文件,这是可行的。然后,我必须修改应用程序,使其从给定文件夹中读取,而不是从resources文件夹中读取。这是我应该做的吗
我对Java还比较陌生,所以请放轻松。在jar文件中存储初始的默认属性,因为参考资料很好
但是如果您希望它们是可写的,那么您需要将它们作为文件存储在磁盘上的某个位置。通常,在.yourapp目录下或用户主目录中的.yourapp文件中
因此,请尝试查找该文件,如果不存在,请返回资源。写入时,请始终写入文件。这是一个示例代码,可用于此操作。在项目根目录中创建一个配置文件夹,在其中放置app.properties文件
package com.yourparckage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
/* Create basic object */
private ClassLoader objClassLoader = null;
private Properties commonProperties = new Properties();
public static final String CONFIG_FILE = "config/app.properties";
/**
* This method loads config data from properties file
*
*/
public Config() {
objClassLoader = getClass().getClassLoader();
}
public String readKey(String propertiesFilename, String key)
{
/* Simple validation */
if (propertiesFilename != null && !propertiesFilename.trim().isEmpty() && key != null
&& !key.trim().isEmpty()) {
/* Create an object of FileInputStream */
InputStream objFileInputStream = null;
/**
* Following try-catch is used to support upto 1.6. Use try-with-resource in JDK
* 1.7 or above
*/
try {
/* Read file from resources folder */
objFileInputStream = new FileInputStream(propertiesFilename);
/* Load file into commonProperties */
commonProperties.load(objFileInputStream);
/* Get the value of key */
return String.valueOf(commonProperties.get(key));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
/* Close the resource */
if (objFileInputStream != null) {
try {
objFileInputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
return null;
}
}我建议检查java.util.prefs.Preferences类,因为这样可以将数据存储在适合OS Windows注册表、.directroy、~/Library/Application Support的位置