java 更新properties配置文件

今天遇到个需求需要更新工程中的properties配置文件,但是在网上找了一堆方案(java.util.properties以及apache.commons.configuration.PropertiesConfiguration等)测试遇到一个共同的问题,无法将修改后的文件流写入到磁盘中持久化。最后发现问题出在properties文件的路径上,网上现有的示例代码都是采用的相对路径如:File file = new File("engine.properties"),此处换成绝对路径即可。

java类中获取绝对路径方法如下:

String filePath = yourClassName.class.getResource("/").getPath()+"engine.properties";

返回结果如下:C:\apache-tomcat-7.0.68\webapps\readydesk\WEB-INF\classes\

其中,getResource("/")返回classpath的位置

getResource("")返回类所在包名,如:C:\apache-tomcat-7.0.68\webapps\readydesk\WEB-INF\classes\com\test\impl\


现给出我的代码:

1.基于java.util.properties

优点在于无需引入额外的jar包,但有一个明显的缺点:通过这种方式修改的properties文件,其键值对顺序会乱。

String profilepath =PropertyUtil.class.getResource("/").getPath()+"config.properties";//我的配置文件在src根目录下try {

        Properties props=new Properties();

                props.load(new FileInputStream(profilepath));

                OutputStream fos =new FileOutputStream(profilepath);         

                props.setProperty("参数", "参数值");

                props.store(fos, "Update value");

                fos.close();

            } catch (IOException e) {

            e.printStackTrace();

                System.err.println("属性文件更新错误");

            }

2.基于apache.commons.configuration.PropertiesConfiguration

这种方式不会造成写入的键值对顺序紊乱(配置文件里面参数多的情况下极力推荐),不过需要引入commons-configuration包(带引入此包在抛出ConfigurationException异常时或报错,报错内容如下:No exception of type ConfigurationException can be thrown; an exception type must be a subclass of Throwable;头部报错:The type

org.apache.commons.lang.exception.NestableException cannot be resolved.

It is indirectly referenced from required .class files

)如出现报错,需要引入commons-lang-2.6.jar以下的版本

示例代码如下:

String profilepath = PropertyUtil.class.getResource("/").getPath()+filepath;

try {

PropertiesConfiguration config = new PropertiesConfiguration(profilepath);

  config.setAutoSave(true);

  config.setProperty(key, value);

                //System.out.println(config.getString(key));

} catch (ConfigurationException e) {

}

猜你喜欢

转载自blog.csdn.net/weixin_33924312/article/details/90830779