Java基础知识强化之IO流笔记66:Properties的概述 和 使用(作为Map集合使用)

1. Properties的概述 

Properties:属性集合类。是一个可以和IO流相结合使用的集合类。

该类主要用于读取以项目的配置文件(以.properties结尾的文件 和 xml文件)。


Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串

PropertiesHashtable的子类,说明是一个Map集合

2. Properties作为Map集合使用

 1 package cn.itcast_08;
 2 
 3 import java.util.Properties;
 4 import java.util.Set;
 5 
 6 /*
 7  * Properties:属性集合类。是一个可以和IO流相结合使用的集合类。
 8  * Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。 
 9  * 
10  * 是Hashtable的子类,说明是一个Map集合。
11  */
12 public class PropertiesDemo {
13     public static void main(String[] args) {
14         // 作为Map集合的使用
15         // 下面这种用法是错误的,一定要看API,如果没有<>,就说明该类不是一个泛型类,在使用的时候就不能加泛型
16         // Properties<String, String> prop = new Properties<String, String>();
17 
18         Properties prop = new Properties();
19 
20         // 添加元素
21         prop.put("it002", "hello");
22         prop.put("it001", "world");
23         prop.put("it003", "java");
24 
25         // System.out.println("prop:" + prop);
26 
27         // 遍历集合
28         Set<Object> set = prop.keySet();
29         for (Object key : set) {
30             Object value = prop.get(key);
31             System.out.println(key + "---" + value);
32         }
33     }
34 }

运行效果,如下:

原文地址:https://www.cnblogs.com/hebao0514/p/4876782.html