1.1 Properties作为Map集合的使用
1. Properties介绍
- Properties 是一个Map体系的集合类
- Properties可以保存到流中或从流中加载
- 属性列表中的每个键及其对应的值都是一个字符串
2. Properties基本使用示例代码:
1.2 Properties作为Map集合的特有方法
1. 特有方法
方法名 | 说明 |
---|
Object setProperty(String key,String value) | 设置集合的键和值,都是String类型,底层调用 Hashtable方法 put |
String getProperty(String key) | 使用此属性列表中指定的键搜索属性 |
Set stringPropertyNames() | 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串 |
2. 示例代码
import java.util.Properties;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Properties prop = new Properties();
prop.setProperty("001", "小明");
prop.setProperty("002", "小红");
prop.setProperty("003", "小王");
Set<String> names = prop.stringPropertyNames();
for (String key : names) {
String value = prop.getProperty(key);
System.out.println(key + "," + value);
}
}
}
1.3 Properties和IO流相结合的方法
1. 和IO流结合的方法
方法名 | 说明 |
---|
void load(InputStream inStream) | 从输入字节流读取属性列表(键和元素对) |
void load(Reader reader) | 从输入字符流读取属性列表(键和元素对) |
void store(OutputStream out, String comments) | 将此属性列表(键和元素对)写入此 Properties表中,以适合于使用load(InputStream)方法的格式写入输出字节流 |
void store(Writer writer, String comments) | 将此属性列表(键和元素对)写入此 Properties表中,以适合使用 |
2. 示例代码
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class Demo {
public static void main(String[] args) throws IOException {
myLoad();
}
private static void myLoad() throws IOException {
Properties prop = new Properties();
FileReader fr = new FileReader("myOtherStream\\fw.txt");
prop.load(fr);
fr.close();
System.out.println(prop);
}
private static void myStore() throws IOException {
Properties prop = new Properties();
prop.setProperty("001", "小明");
prop.setProperty("002", "小红");
prop.setProperty("003", "小王");
FileWriter fw = new FileWriter("myOtherStream\\fw.txt");
prop.store(fw, null);
fw.close();
}
}