/*
* Properties集合
* 特点:1、该集合中的键和值都是字符串类型
* 2、集合中的数据可以保存到流中,也可以从流中获取
* 用处:
* 通常该集合用于操作以键值对形式存在的配置文件
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo {
public static void main(String[] args) {
//创建一个Properties集合
Properties properties = new Properties();
//增加元素
properties.setProperty("04", "eboy");
properties.setProperty("05", "FRR");
properties.setProperty("06", "GXY");
//增加元素1:从文件中获取,必须要保证文件中的数据是键值对
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream("properties.txt");
properties.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//取出元素
Set<String> names = properties.stringPropertyNames();
for (String str : names){
System.out.println(properties.getProperty(str));
}
//修改元素
properties.setProperty("02", "奉猪");
//删除元素
properties.remove("02");
//list方法,可列出集合内所有的键值
properties.list(System.out);
//story方法,可保存集合内所有的键值到硬盘上
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream("properties.txt");
try {
properties.store(outputStream, "No=Name");
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}