java.util.Properties
Properties是hashtable的子类。
也就是说他具备了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 | 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。 |
存取配置文件
取:prop.load(file)//prop为Properties对象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();
}
}