Properties 类
简述
Properties
类为
Hashtable
的子类,是一个实现Map接口的集合类,能够用来生成配置文件。
Properties
类表示一组持久的属性。
Properties
可以保存到流中或从流中加载。 属性列表中的每个键及其对应的值都是一个字符串。
属性列表可以包含另一个属性列表作为其“默认值”; 如果在原始属性列表中找不到属性键,则会搜索此第二个属性列表。
常用类方法
设置属性:
因为
Properties
从继承
Hashtable
时,
put
种
putAll
方法可应用于
Properties
对象。 强烈不鼓励使用它们,因为它们允许调用者插入其键或值不是
Strings
。应该使用
setProperty
方法。如果
store
或
save
方法在包含非
String
键或值的“受损害”
Properties
对象上调用,则调用将失败。类似地,如果在包含非
String
密钥的“受损害”
Properties
对象上调用
propertyNames
或
list
方法的调用将失败。
设置属性后,需要再次调用store方法存到文件中
Properties pro=new Properties();
pro.setProperty("count", "1");//不建议使用put和putAll方法,写入都为String
遍历属性文件:
Set<Entry<Object, Object>> entry= pro.entrySet(); //无自定义泛型
for(Entry<Object,Object> e:entry){
System.out.println("属性:"+e.getKey()+" 值:"+e.getValue());
}
读取属性:
value=pro.getProperty("count");
存储属性文件:
Store()方法接受一个Outputstream或Writer,以及一个用于描述文件属性的字符串
pro.store(new FileWriter(new File("路径")), "properties");
加载属性文件:
Load()方法接受一个Inputstream或Reader
pro.load(new FileReader(new File("路径")));
使用实例
实现功能:一个程序运行3次后无法再次运行。
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class Demo2 {
public static void main(String[] args) throws IOException {
Properties pro=new Properties();// 创建properties
int count=0;
String value=null;
File f=new File("E://pro.properties");
if(!f.exists()){//判断属性文件是否存在,不存在,则创建新文件
f.createNewFile();
}
pro.load(new FileReader(f));//加载属性文件
value=pro.getProperty("count");//获取count属性值
if(value!=null){
count=Integer.parseInt(value);
}
if(count>=3){
System.out.println("无法运行!");
System.exit(0);
}else{
count++;
System.out.println("运行"+count+"次!");
}
pro.setProperty("count", count+"");//重新设置属性值
pro.store(new FileWriter(new File("E://pro.properties")), "properties");//保存配置文件
}
}