Properties简介
-
Properties:属性集对象,其实就是一个Map集合
-
Properties代表的是一个属性文件,可以把键值对的数据存入到一个属性文件中去
- 属性文件:后缀是.properties结尾的文件,里面的内容都是key=value
写入属性文件
//Properties的方法
public Object setProperty(String key, String value)//保存一对属性。
public String getProperty(String key) //使用此属性列表中指定的键搜索属性值
public Set<String> stringPropertyNames() //所有键的名称的集合
public void store(OutputStream out, String comments)//保存数据到属性文件中去
public void store(Writer fw, String comments)//保存数据到属性文件中去
示例
- 需求:使用Properties对象生成一个属性文件,里面存入用户名和密码信息
public class PropertiesDemo01{
public static void main(String[] args) throws Exception{
// a.创建一个属性集对象:Properties对象
Properties properties = new Properties();
properties.setProperty("admin","123456");
properties.setProperty("dllei","101333");
System.out.println(properties);
// b.把属性集对象的数据存入到属性文件中去
OutputStream os = new FileoutStream("filepath");
/*
第一个参数:被保存的数据的输出管道
第二个参数:commit
*/
properties.store(os,"commit");
}
}
读取属性文件
public synchronized void load(InputStream inStream)//加载属性文件的数据到属性集对象中去
public synchronized void load(Reader fr)//加载属性文件的数据到属性集对象中去
- 需求:Properties读取属性文件中的键值对信息
public class PropertiesDemo02{
public static void main(String[] args) throws Exception{
// 1.创建一个属性集对象
Properties properties = new Properties();
// 2.字节输入流加载属性文件数据到属性集对象properties中
properties.load(new FileInputStream("filepath"));
System.out.println(properties);
System.out.println(properties.getProperty("dlei"));
System.out.println(properties.getProperty("admin"));
}
}
网友评论