java properties 保存_Java 读写Properties配置文件
轉自:https://www.cnblogs.com/xudong-bupt/p/3758136.html
1.Properties類與Properties配置文件
Properties類繼承自Hashtable類并且實現了Map接口,也是使用一種鍵值對的形式來保存屬性集。不過Properties有特殊的地方,就是它的鍵和值都是字符串類型。
2.Properties中的主要方法
(1)load(InputStream inStream)
這個方法可以從.properties屬性文件對應的文件輸入流中,加載屬性列表到Properties類對象。如下面的代碼:
Properties pro = new Properties();
FileInputStream in = new FileInputStream("a.properties");
pro.load(in);
in.close();
(2)store(OutputStream out, String comments)
這個方法將Properties類對象的屬性列表保存到輸出流中。如下面的代碼:
FileOutputStream oFile = new FileOutputStream(file, "a.properties");
pro.store(oFile, "Comment");
oFile.close();
如果comments不為空,保存后的屬性文件第一行會是#comments,表示注釋信息;如果為空則沒有注釋信息。
注釋信息后面是屬性文件的當前保存時間信息。
(3)getProperty/setProperty
這兩個方法是分別是獲取和設置屬性信息。
3.代碼實例
屬性文件a.properties如下:
name=root
pass=liu
key=value
讀取a.properties屬性列表,與生成屬性文件b.properties。代碼如下:
1 import java.io.BufferedInputStream;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.util.Iterator;
6 import java.util.Properties;
7
8 public class PropertyTest {
9 public static void main(String[] args) {
10 Properties prop = new Properties();
11 try{
12 //讀取屬性文件a.properties
13 InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
14 prop.load(in); ///加載屬性列表
15 Iterator it=prop.stringPropertyNames().iterator();
16 while(it.hasNext()){
17 String key=it.next();
18 System.out.println(key+":"+prop.getProperty(key));
19 }
20 in.close();
21
22 ///保存屬性到b.properties文件
23 FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打開
24 prop.setProperty("phone", "10086");
25 prop.store(oFile, "The New properties file");
26 oFile.close();
27 }
28 catch(Exception e){
29 System.out.println(e);
30 }
31 }
32 }
總結
以上是生活随笔為你收集整理的java properties 保存_Java 读写Properties配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中native_java中的na
- 下一篇: java垃圾回收机制优化_JVM性能优化