一, Properties 概述
Properties 是 Hashtable 的子类, 不允许 key 和 value 是 null, 并且它的 key 和 value 的类型都是 String.
二, 常用方法
1, 构造方法
Properties(): 创建一个无默认值的空属性列表.
Properties(Properties defaults): 创建一个带有指定默认值的空属性列表
2, 获取方法
String getProperty(String key): 用指定的键在此属性列表中搜索属性.
String getProperty(String key, String defaultValue): 用指定的键在属性列表中搜索属性
3, 设置方法
Object setProperty(String key, String value): 调用 Hashtable 的方法 put.
4, 其他方法
void load(InputStream inStream): 从输入流中读取属性列表 (键和元素对).
void load(Reader reader) : 按简单的面向行的格式从输入字符流中读取属性列表 (键和元素对).
Demo:
- @Test
- public void test1(){
- Properties pro = new Properties();
- pro.setProperty("user", "root");
- pro.setProperty("pwd", "123456");
- String user = pro.getProperty("user");
- String password = pro.getProperty("pwd");
- System.out.println(user);
- System.out.println(password);
- }
- @Test
- public void test2() throws IOException{
- Properties pro = new Properties();
- pro.load(TestMapImpl.class.getClassLoader().getResourceAsStream("jdbc.properties"));
- String user = pro.getProperty("user");
- String password = pro.getProperty("password");
- System.out.println(user);
- System.out.println(password);
- }
- @Test
- public void test3() throws IOException{
- Properties pro = System.getProperties();// 获取系统属性配置
- Set entrySet = pro.entrySet();
- for (Object entry : entrySet) {
- System.out.println(entry);
- }
- }
来源: http://www.bubuko.com/infodetail-3344483.html