我的属性文件包含3个属性,我需要覆盖thirdOne的值。如何从Java代码中的类路径加载属性文件并覆盖它。.
我的属性文件位置packagName-> resource-> folderName->。propertyFile
属性文件:我需要覆盖“ epochFromTime”的值:
FILE_PATH=C:\\Users\\pda\\Desktop\\JsonOutput\\DataExtract
epochFilename=C:\\Users\\pda\\Desktop\\JsonOutput\\epochTime.txt
epochFromTime=1545329531862
Java代码:
try {
Properties config = new Properties();
config.load(ClassLoader.getSystemResourceAsStream(PROPERTIES_PATH));
String epochFromTimeChanged= Long.toString(epoch_to2);
config.setProperty("epochFromTime",epochFromTimeChanged);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
这很容易。首先,将属性文件读取到Properties
。然后更新并保存。不要忘记关闭资源。
public static void updateProperties(File file, Consumer<Properties> consumer) throws IOException {
Properties properties = new Properties();
try (Reader reader = new BufferedReader(new FileReader(file))) {
properties.load(reader);
}
consumer.accept(properties);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
properties.store(writer, "comment");
}
}
客户端代码如下:
updateProperties(
new File("application.properties"),
properties -> {
properties.setProperty("two", "two_two_two");
properties.setProperty("three", "three_three");
});
application.properties
更新前
two=two_two
one=one_one
更新后
#comment
#Fri Jan 04 18:59:12 MSK 2019
two=two_two_two
one=one_one
three=three_three
答案 1 :(得分:0)
使用Properties.store()
将更改后的值写回文件:
String PROPERTIES_PATH = "...";
try {
File f = new File(PROPERTIES_PATH);
FileInputStream in = new FileInputStream(f);
Properties config = new Properties();
config.load(in);
String epochFromTimeChanged= Long.toString(epoch_to2);
config.setProperty("epochFromTime",epochFromTimeChanged);
// get or create the file
File f = new File(PROPERTIES_PATH);
OutputStream out = new FileOutputStream(f);
config.store(out, "My properties file comment");
} catch (FileNotFoundException e1) {
log.info("{} does not exist", PROPERTIES_PATH);
} catch (IOException e) {
log.error("Cannot access {}", PROPERTIES_PATH, e);
}