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 = DemonstrateRestService.class.getResource("/").getPath()+"engine.properties";//我的配置文件在src根目录下
   try {
        Properties props=new Properties();
                props.load(new FileInputStream(profilepath));
                OutputStream fos = new FileOutputStream(profilepath);          
                props.setProperty("server.uiserverport", "443");
                props.store(fos, "Update value");
                fos.close();
            } catch (IOException e) {
            e.printStackTrace();
                System.err.println("属性文件更新错误");
            }

 

 
2.基于apache.commons.configuration.PropertiesConfiguration
这种 方式不会造成写入的键值对顺序紊乱(配置文件里面参数多的情况下极力推荐),不过 需要引入commons-configuration包
 
示例代码如下:
String profilepath = DemonstrateRestService.class.getResource("/").getPath()+"engine.properties"
try
        {
        PropertiesConfiguration config  = new PropertiesConfiguration(profilepath);
            String uiserverport = config.getString("server.uiserverport");
            config.setAutoSave(true);
            config.setProperty("server.uiserverport", "445");
            System.out.println(config.getString("server.uiserverport"));
        }
        catch(ConfigurationException cex)
        {
        System.err.println("loading of the configuration file failed");
        }

 

转载于:https://www.cnblogs.com/gavinwangxj/p/7112115.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值