已解决
java修改properties文件内容(读取、修改、追加)
来自网友在路上 160860提问 提问时间:2023-11-01 07:22:27阅读次数: 60
最佳答案 问答题库608位专家为你答疑解惑
PropertiesConfiguration 是 Apache 帮我们实现按照文件的顺序读取properties文件的类,Properties类能做的它都能做。不仅如此,他还有许多方便实用的附加功能。
工具类:
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class PropertiesUtil {private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);private static final String NATIVE_FILE_ADDRESS = "zta-monitor-api/src/main/resources/dev/statistics.properties";private static final String DEPLOY_FILE_ADDRESS = "export/App/conf/statistics.properties";public static void setValueToProperties(String key, String value) {try {PropertiesConfiguration propsConfig = new PropertiesConfiguration(DEPLOY_FILE_ADDRESS);propsConfig.setAutoSave(true);propsConfig.setProperty(key, value);} catch (Exception e) {logger.error("setValueToProperties error : {}", e.getMessage());}}public static void addValueToProperties(String key, String value) {try {PropertiesConfiguration propsConfig = new PropertiesConfiguration(DEPLOY_FILE_ADDRESS);// 修改属性之后自动保存,省去了propsConfig.save()过程propsConfig.setAutoSave(true);propsConfig.addProperty(key, value);} catch (Exception e) {logger.error("addValueToProperties error : {}", e.getMessage());}}public static String getValueFromProperties(String key) {String res = null;try {PropertiesConfiguration propsConfig = new PropertiesConfiguration(DEPLOY_FILE_ADDRESS);res = propsConfig.getString(key);} catch (Exception e) {logger.error("getValueFromProperties error : {}", e.getMessage());}return res;}public static void main(String[] args) {try {setValueToProperties("name2", "testError");addValueToProperties("name4", "test4");String name2 = getValueFromProperties("name4");System.out.println(name2);} catch (Exception e) {e.printStackTrace();}}
}
除此之外,还可以 propsConfig.setEncoding("utf-8") 设置编码。
需要的maven依赖:
<dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.10</version>
</dependency>
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"java修改properties文件内容(读取、修改、追加)":http://eshow365.cn/6-29217-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!