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