Java I/O——Properties类 配置文件类

Properties 类

 

简述

 

 

 

Properties类为 Hashtable的子类,是一个实现Map接口的集合类,能够用来生成配置文件。
Properties类表示一组持久的属性。 Properties可以保存到流中或从流中加载。 属性列表中的每个键及其对应的值都是一个字符串。

 

属性列表可以包含另一个属性列表作为其“默认值”; 如果在原始属性列表中找不到属性键,则会搜索此第二个属性列表。

 

常用类方法

 

设置属性:

 

因为 Properties从继承 Hashtable时, putputAll方法可应用于 Properties对象。 强烈不鼓励使用它们,因为它们允许调用者插入其键或值不是 Strings。应该使用 setProperty方法。如果 storesave方法在包含非 String键或值的“受损害” Properties对象上调用,则调用将失败。类似地,如果在包含非 String密钥的“受损害” Properties对象上调用 propertyNameslist方法的调用将失败。
设置属性后,需要再次调用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");//保存配置文件
	}

}
 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值