Properties(键值)对象

java.util.Properties

Propertieshashtable的子类。

也就是说他具备了map集合的特点,而且它里面存储的键值对都是字符串

是集合中IO技术相结合的集合容器

该对象特点:可以用于键值对相匹配形式的配置文件

 

 

可以直接从流中获取键值对;

 

在加载数据时需要数据有固定的格式:键=

#不加载:可以理解为注释

public classTextProperties {

publicstatic String getValue(String str,String key) {

//类加载器来加载文件

InputStreamis=ClassLoader.getSystemResourceAsStream(str);

 

Propertiesprop=new Properties();

try{

prop.load(is);

Stringbm=prop.getProperty(key);

returnbm;

 

}catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}finally{

try{

if(null!=is)

is.close();

}catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

}

returnnull;

}

}


设置和获取元素

Properties prop= newProperties();

//设置键值对,默认以“=”链接

prop.setProperty(String,String);

//获取

prop.getProperty();

//获取所有的键

Set<String>stringPropertyNames()

//修改值

prop.setProperty("","");

 

输出到流中

void

list(PrintStream out)

将属性列表输出到指定的输出流。

void

list(PrintWriter out)

将属性列表输出到指定的输出流

输入流中读取

void

load(InputStream inStream)

从输入流中读取属性列表(键和元素对)。

void

load(Reader reader)

按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。

 

 

存取配置文件

取:prop.load(file)//propProperties对象file为文件流

原理:

1、用一个流和文件关联

2、取一行数据,将该行数据用'='分割。

3=左边为键,右边为值,存储到properties集合中即可

改:

当需要改文件中的元素时,直接将prop集合中的键值改掉,然后再用store();方法将prop存入输出流中



一个例子:

/*
用于记录程序的运行次数。如果使用次数已到,那么给出注册提示
由于每次软件后退出都会清理内存,所以应该建立一个配置文件,用来存储键值信息
键值对数据是map集合。
数据是以文件形式存储,使用IO技术
那么 map+IO———>Properties.
*/
import java.util.*;
import java.io.*;
class Runcount
{
	public static void main(String[] args) throws IOException
	{
		Properties prop=new Properties();
		File file=new File("count.ini");
		if(!file.exists())//如果文件不存在,创建一个文件
			file.createNewFile();
		FileInputStream fis=new FileInputStream(file);
		prop.load(fis);

		int count=0;
		String value = prop.getProperty("time");
		if(value!=null)//首次运行value的值为null,如果不等于空则获取value的值
			count=Integer.parseInt(value);
		count++;
		prop.setProperty("time",count+"");
		FileOutputStream fos = new FileOutputStream(file);
		prop.store(fos,"");
		fos.close();
		fis.close();

	}
}






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值