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") 设置编码。文章来源:https://www.toymoban.com/news/detail-735740.html
需要的maven依赖:文章来源地址https://www.toymoban.com/news/detail-735740.html
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
到了这里,关于java修改properties文件内容(读取、修改、追加)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!