java实现对properties类型文件的读写

在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();
	}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值