Properties類表示一個持久的屬性集。Properties可保存在流中或從流中加載。Properties對象只能加載以 .Properties 為后綴的文件(文件我創建在src下)。
開始時文件中沒有內容,我運行的順序是先寫入在進行讀取
一、Properties讀取文件內容
我們要做的第一步就是要將文件讀取Properties類對象中,由於load 有一個參數是InputStream,所以我們可以用InputStream的子類FileInputStream降屬性文件讀取到Properties對象中,知道db.properties的路徑,我們就用FileInputStream(String name)構造函數。
public static void input(){ //創建Properties對象 Properties properties = new Properties(); //獲取輸入流對象 try { //方法一:必須給予一個文件的絕對路徑 FileInputStream inputStream = new FileInputStream(new File("D:\\BaiduNetdiskDownload\\eclipse-jee-kepler-R-win64(1)\\workspace2\\properties\\src\\db.properties")); //Properties加載數據流對象 properties.load(inputStream); //獲取數據
System.out.println("userName: "+properties.get("userName"));
System.out.println("password: "+properties.get("passwrod"));
} catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // try { // //方法二:使用類加載器可以直接獲取類(src)路徑下的文件,不必是文件的絕對路徑 // InputStream inputStream = test.class.getClassLoader().getResourceAsStream("db.properties"); // properties.load(inputStream); // //獲取數據 // System.out.println("userName: "+properties.get("userName"))
// System.out.println("password: "+properties.get("passwrod"));
// } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } }
二、properties寫入文件內容
最開始寫的時候,我只是用properties類進行文件的讀取,並沒有進行過文件內容的寫入,開始時遇到了一個問題(開始時
properties.setProperty("userName", "aaa")這個賦值的操作我是寫在流之后的),導致想寫入的內容寫不進去。最后發現需要將它寫在流前面(別問為什么,用法是這樣的,哈哈)。
public static void output(){ try { Properties properties = new Properties();
//如果we年中存在了相同的key,這個操作代表是給這個key賦新的值,如果不存在,代表是寫入新的鍵值對 properties.setProperty("userName", "aaa"); properties.setProperty("passwrod", "123456"); FileOutputStream outputStream = new FileOutputStream(new File("D:\\BaiduNetdiskDownload\\eclipse-jee-kepler-R-win64(1)\\workspace2\\properties\\src\\db.properties")); properties.store(outputStream, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
三、 運行結果: