java 读写 properties_java读写xxx.properties文件实用小例

自己写了一个读取properties的程序,废话不说了,直接上代码:(附件中有eclipse的工程源码)

package my.config;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Properties;

import my.util.ResourceUtil;

import my.util.StringUtil;

/**

* 读取xxx.properties文件

* @author zs

*

*/

public class Config {

private final static String CONFIG_NAME = "config.properties";

private static Properties pro = null;

/**

* 获取文件的Properties

* @param fileName

*/

public static Properties getConfigInfo(){

try{

InputStream in = ResourceUtil.getResourceStream(StringUtil.nvl(CONFIG_NAME));

pro = new Properties();

pro.load(in);

in.close();//注意要关闭

return pro;

}catch(Exception e){

e.printStackTrace();

System.out.println("获取 Porperties失败");

return null;

}

}

/**

* 根据key值,读取value

* @param key

* @return

*/

public static String readConfig(String key){

try{

if(pro==null){

pro = getConfigInfo();

}

String value = StringUtil.nvl(pro.getProperty(key));

System.out.println("读取成功!");

if(("").equals(value)){

System.out.println("没有找到"+key+"对应的值");

}

return value;

}catch(Exception e){

e.printStackTrace();

System.out.println("读取失败!");

return "";

}

}

/**

* 根据key 和value 值 ,写入配置文件中,如果key存在,就做修改,如果不存在,就做增加

* @param key

* @param value

*/

public static void writeConfig(String key , String value){

try{

if(pro==null){

pro = getConfigInfo();

}

String realPath = ResourceUtil.getResourceRealPath(StringUtil.nvl(CONFIG_NAME));

OutputStream fos = new FileOutputStream(realPath);

pro.setProperty(key, value);

pro.store(fos, "Update '" + key + "' value");

fos.close();

getConfigInfo();

System.out.println("写入成功!");

System.out.println("写入的内容为:"+key+"="+value);

}catch(Exception e){

System.out.println("写入失败!");

e.printStackTrace();

}

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-10-14 14:13

浏览 1212

评论

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值