Properties配置文件說明
- Properties類對應.properties文件。文件內容是鍵值對,鍵值對之間使用"="或空格隔開。開頭是"#"的表示注釋
- Properties類在加載.properties文件時使用的iso8859-1的編碼。所以這個文件中的中文要特殊處理:如果這個配置文件中有中文就必須要進行轉義,使用native2ascii.exe命令操作:
native2ascii d:/my.properties d:/my2.properties
??? 使用Properties類中的load(InputStream) 方法可以加載配置文件,使用其中的store(OutputStream) 方法可以保存配置到指定文件。
??? 更多的信息可以看Properties類的API文檔。
加載配置文件
public static void testLoadProperties() throws Exception {Properties properties = new Properties();InputStream in = new FileInputStream("E:/itcast/config.properties");properties.load(in); // 加載 in.close();System.out.println(properties); }
寫配置文件
public static void testStoreProperties() throws Exception {// 準備配置信息Properties properties = new Properties();properties.setProperty("name", "李四");properties.setProperty("age", "20");// 準備OutputStream out = new FileOutputStream("d:/my.properties");String comments = "這是我的配置文件";// 寫出去 properties.store(out, comments);out.close(); }
示例代碼:
public class DBUtil {static Properties properties = new Properties();static{try {Class clazz = DBUtil.class;InputStreamReader fileReader =new InputStreamReader(clazz.getResourceAsStream("/db.properties"));properties.load(fileReader);} catch (IOException e) {e.printStackTrace();}}public static String getUserName(){String userName =properties.getProperty("userName");return userName;}public static String getPassword(){return properties.getProperty("password");}public static void main(String[] args) {System.out.println("用戶名:"+ getUserName());System.out.println("密碼: "+ getPassword());} }
?
特點:
1. 鍵和值都是字符串
2. 可以和IO流進行配合使用
父類是 Hashtable
特有的功能:
public Object setProperty(String key , String value) ;
public String getProperty(String key) ;
public Set<String> stringPropertyNames() ;
public void load(Reader r)
public void load(InputStream in)
public void store(Writer w)
public void store(OutputStream out)
?
?
?