java读写properties配置文件方法
1、Properties類
Properties類表示了一個持久的屬性集。Properties可保存在流中或從流中加載,屬性列表中的key和value必須是字符串。
雖然Properties類繼承了java.util.Hashtable,可以使用Hashtable的put等方法,但是這些方法允許使用非string類型的數據,將導致不安全的行為,所以還是應該使用setProperty 方法。
2、主要方法
load(InputStream in) ?從輸入流讀取屬性列表
getProperties(String key) ?獲取指定key的值,返回string
setProperty(String key, String value) ?設置或修改屬性的值
store(OutputStream out, String comments) ?將properties對象寫入一個輸出流,comments為注釋,comments為空則不加注釋
下面進行代碼演示
1 /*初始配置文件 2 aa=1 3 bb=2 4 cc=3 5 */ 6 7 Properties prop = new Properties(); //創建Properties對象 8 InputStream in = null; 9 FileOutputStream oFile = null; 10 try { 11 in = new FileInputStream("filePath"); //創建輸入流文件對象 12 prop.load(in); //加載輸入流 13 System.out.println("aa=" + prop.getProperty("aa")); //aa=1 14 prop.setProperty("aa", "11"); //修改"aa"的值 15 oFile = new FileOutputStream("filePath"); //創建輸出流文件對象 16 prop.store(oFile, ""); //將Properties對象的屬性保存到輸出流指定文件 17 } catch (IOException e) { 18 log.error(e); 19 } finally { 20 try { 21 oFile.close(); //關閉輸出流 22 } catch (IOException e) { 23 log.error(e); 24 } 25 try { 26 in.close(); //關閉輸入流 27 } catch (IOException e) { 28 log.error(e); 29 } 30 }最后的關閉IO流很重要,一定要放在finally代碼塊中執行。
3、修改properties配置文件時遇到的一些問題
讀取配置文件一般不會出什么問題,修改和寫入的時候稍微復雜一點,把遇到的問題記錄一下
3.1 配置FileOutputStream的第二個參數true,導致配置文件末尾重復追加配置項
FileOutputStream構造函數
FileOutputStream(String name, boolean append)
append代表是否向文件末尾追加字符流的形式寫入文件,默認為false,即重新寫入配置
此處的輸出流配置第二個參數為true會導致不停的在配置文件末尾追加重復的配置,導致輸出流指定的文件越來越大。所以最好不加這個參數
1 /*初始配置文件 2 aa=1 3 bb=2 4 cc=3 5 */ 6 7 Properties prop = new Properties(); 8 InputStream in = new FileInputStream("filePath"); 9 prop.load(in); 10 prop.setProperty("aa", "11"); 11 FileOutputStream oFile = new FileOutputStream("filePath", true); 12 prop.store(oFile, ""); 13 14 /*執行后配置文件 15 aa=1 16 bb=2 17 cc=3 18 19 aa=11 20 bb=2 21 cc=3 22 */3.2?FileOutputStream創建位置導致詭異事情
主要是與setProperty()方法的相對位置
正常是先setProperty()設置屬性,然后創建FileOutputStream對象
1 /*初始配置文件 2 aa=1 3 bb=2 4 cc=3 5 */ 6 7 //正常寫法 8 InputStream in = new FileInputStream("filePath"); 9 prop.load(in); 10 prop.setProperty("aa", "11"); 11 FileOutputStream oFile = new FileOutputStream("filePath"); 12 prop.store(oFile, ""); 13 14 //問題寫法 15 InputStream in = new FileInputStream("filePath"); 16 FileOutputStream oFile = new FileOutputStream("filePath"); //提前創建 17 prop.load(in); 18 prop.setProperty("aa", "11"); 19 prop.store(oFile, ""); 20 21 /*正常執行后的配置文件 22 aa=11 23 bb=2 24 cc=3 25 */ 26 27 /*問題執行后的配置文件 28 aa=11 29 */如果反過來,會導致除setProperty()修改的屬性,其它都會丟失。
沒想明白這是為什么,有人明白可以指點一下。
3.3?讀取和修改properties文件后改變文件內容順序
使用jdk提供的Properties類讀取和修改配置文件后,加載到內存中的順序是隨機的,不能保證和原文件的順序一致,因此需要重寫Properties類,實現順序讀取properties屬性。
?
轉載于:https://www.cnblogs.com/wangzhisdu/p/7815193.html
總結
以上是生活随笔為你收集整理的java读写properties配置文件方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Active Diretory 全攻略(
- 下一篇: JQuery选择器——基本筛选选择器和内