Java 之 Properties 集合

一、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

 1   @Test
 2     public void test1(){
 3         Properties pro = new Properties();
 4         pro.setProperty("user", "root");
 5         pro.setProperty("pwd", "123456");
 6         
 7         String user = pro.getProperty("user");
 8         String password = pro.getProperty("pwd");
 9         System.out.println(user);
10         System.out.println(password);
11     }
12 
13   @Test
14     public void test2() throws IOException{
15         Properties pro = new Properties();
16         pro.load(TestMapImpl.class.getClassLoader().getResourceAsStream("jdbc.properties"));
17         
18         String user = pro.getProperty("user");
19         String password = pro.getProperty("password");
20         System.out.println(user);
21         System.out.println(password);
22     }
23 
24   @Test
25     public void test3() throws IOException{
26         Properties pro = System.getProperties();//获取系统属性配置
27         Set entrySet = pro.entrySet();
28         for (Object entry : entrySet) {
29             System.out.println(entry);
30         }
31     }
原文地址:https://www.cnblogs.com/niujifei/p/12079874.html