今天遇到个需求需要更新工程中的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"); }