1. 程式人生 > 實用技巧 >IO和Properties的聯合使用

IO和Properties的聯合使用

IO流:檔案的讀和寫

Properties:是一個Map集合,key和value都是String型別

 1 package IoTest;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.util.Properties;
 7 
 8 public class IOandPropertiesTest {
 9     
10     public static void main(String[] args) throws
Exception{ 11 /* 12 * Properties是一個Map集合,key和value都是String型別。 13 * 想將userinfo檔案中的資料載入到Properties物件當中 14 * 15 * 以後經常改變的資料可以單獨寫到一個檔案中,使用程式動態讀取。將來只需要修改這個檔案的內容,java程式碼不需要做改動,不需要重新編譯, 16 * 伺服器也不需要重啟,就可以獲得動態資訊 17 * 18 * 類似於以上機制的這種檔案可以被稱為配置檔案,並且當配置檔案的內容格式是:
19 * key1=value; 20 * key2=value; 21 * 的時候,將這種配置檔案稱為屬性配置檔案。 22 * 23 * java規範中有要求:屬性配置檔案建議以properties結尾,但這不是必須的。以.properties結尾的檔案在java中被稱為屬性配置檔案, 24 * 其中Properties是專門存放屬性配置檔案內容的一個類 25 */ 26 27 //新建輸入流物件 28 FileReader reader=new
FileReader("userinfo"); 29 30 //新建一個Map集合 31 Properties pro=new Properties(); 32 33 //呼叫Properties物件的Load方法將檔案中的資料載入到Map集合中 34 pro.load(reader); //檔案中的資料順著管道載入到Map集合中,其中"="左邊做key,右邊做value 35 36 //通過key來獲取value 37 String username=pro.getProperty("username"); 38 String password=pro.getProperty("password"); 39 System.out.println(username); 40 System.out.println(password); 41 } 42 43 44 45 }