IO框架(十)补充集合框架Properties
Properties
Properties特点
- 存储属性名和属性值
- 属性名和属性值都是字符串类型
- 没有泛型
- 和流有关
Properties方法
| Modifier and Type |
Method and Description |
String |
getProperty(String key) 使用此属性列表中指定的键搜索属性。 |
String |
getProperty(String key, String defaultValue) 使用此属性列表中指定的键搜索属性。 |
void |
list(PrintStream out) 将此属性列表打印到指定的输出流。 |
void |
list(PrintWriter out) 将此属性列表打印到指定的输出流。 |
void |
load(InputStream inStream) 从输入字节流读取属性列表(键和元素对)。 |
void |
load(Reader reader) 以简单的线性格式从输入字符流读取属性列表(关键字和元素对)。 |
void |
loadFromXML(InputStream in) 将指定输入流中的XML文档表示的所有属性加载到此属性表中。 |
Enumeration<?> |
propertyNames() 返回此属性列表中所有键的枚举,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。 |
void |
save(OutputStream out, String comments) 已弃用 如果在保存属性列表时发生I / O错误,此方法不会抛出IOException。 保存属性列表的store(OutputStream out, String comments)方法是通过store(OutputStream out, String comments)方法或storeToXML(OutputStream os, String comment)方法。 |
Object |
setProperty(String key, String value) 致电 Hashtable方法 put 。 |
void |
store(OutputStream out, String comments) 将此属性列表(键和元素对)写入此 Properties表中,以适合于使用 load(InputStream)方法加载到 Properties表中的格式输出流。 |
void |
store(Writer writer, String comments) 将此属性列表(键和元素对)写入此 Properties表中,以适合使用 load(Reader)方法的格式输出到输出字符流。(comments为注释) |
void |
storeToXML(OutputStream os, String comment) 发出表示此表中包含的所有属性的XML文档。 |
void |
storeToXML(OutputStream os, String comment, String encoding) 使用指定的编码发出表示此表中包含的所有属性的XML文档。 |
Set<String> |
stringPropertyNames() 返回此属性列表中的一组键,其中键及其对应的值为字符串,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。 |
举例1
public class Demo07 {
public static void main(String[] args) throws Exception{
//创建集合
Properties properties=new Properties();
//添加数据
properties.setProperty("username","张三");
properties.setProperty("age","18");
System.out.println(properties.toString());
//遍历
//1.keyset(前面讲过)
//2.entryset(前面讲过)
//3.stringPropertyName()
Set<String> pronames=properties.stringPropertyNames();
for (String proname : pronames) {
System.out.println(proname+":"+properties.getProperty(proname));
}
//和流有关的方法
System.out.println("-----------list方法------------");
//写入练习5.txt文件
PrintWriter pw=new PrintWriter("D:\\练习5.txt");
properties.list(pw);
pw.close();
System.out.println("---------保存store方法------------");
//写入此 Properties表中
FileOutputStream fos=new FileOutputStream("D:\\store.properties");
//store(Writer writer, String comments),其中comments为注释
properties.store(fos,"sxp1");
//load方法加载.properties里(properties表里)的文件内容
Properties properties2=new Properties();
FileInputStream fis=new FileInputStream("D:\\store.properties");
//加载(获得表中的内容)
properties2.load(fis);
fis.close();
//打印内容
System.out.println(properties2.toString());
}
}
//输出:
{age=18, username=张三}
age:18
username:张三
-----------list方法------------
---------保存store方法------------
{age=18, username=张三}