在java项目中,我们通常会有一些配置属性的数据,采用properties文件对数据进行管理是很有必要的,尤其是在属性值改变和项目环境发生变化时,所以特地总结一下对properties文件的最常见的操作。
(一):properties数据文件的数据格式如下图:
文件中的数据采用键值对的形式存储,#表示注释行。
(二):java实现对properties文件的操作
1.读取properties文件
首先我们要获得properties文件,将properties文件读入到流中。
InputStream in=new BufferdInputStream (new FileInputStream("./properties/info.properties"));
其中./表示项目的根目录
然后实例化一个properties对象,并且通过调用load(InputStream inStream)方法将数据流加载到这个properties对象中。
Properties prop=new Properties();
prop.load(in);
然后就可以调用properties类的getProperties(String key)的方法来根据键值获得相应的值
value=prop.getProperty(key);
完整的java代码如下:
public static String getValue(String key){
String value=null;
try{
InputStream in=new BufferdInputStream (new FileInputStream("./properties/info.properties"));
Properties prop=new Properties();
prop.load(in);
value=prop.getProperty(key);
in.close();
if(value!=null){
return value;
}
else{
new Exception("didn't find the key "+key+"'s value");
}
}catch(IOEXception e){
e.printStackTrace();
}
}
2.修改properties文件中的值或者插入新的键值对:
修改值和上面的读取值差不多,只是最后要把文件流写回到相应的文件。
首先也获得将要修改的文件的文件流,然后实例化一个properties对象,并且调用properties类的load(InputStream inStream)方法来
加载相应的文件流,接着调用properties类的setProperties(String key,String value)方法来修改或插入键值对(如果键值存在就是修
改,如果键值不存在就是插入新的键值对)。最后调用properties类的store(OutputStream out,String comments)方法来将修改后的
文件流写入到文件中。
具体java代码实现如下:
//设置键值数据,先读后写的过程
public static void setValue(String key,String value){
Properties prop=new Properties();
try{
InputStream in=new BufferedInputStream(new FileInputStream("./properties/info.properties"));
prop.load(in);
in.close();
prop.setProperty(key,value);
//然后写回到文件
FileOutputStream oFile=new FileOutputStream("./properties/info.properties");
prop.store(oFile,"import information");
oFile.flush();
oFile.close();
}catch(IOException e){
e.printStackTrace();
}
}