读取配置文件 java类


package com.web.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/****
* 读取properties文件
* @author Administrator
*
*/
public class PropertiesReader {

private static PropertiesReader instance = null;

private Properties properties = null;


private PropertiesReader(String path) {
properties = this.createProperties(path);
if (properties == null)
properties = new Properties();
}

/**
* 默认读取struts.propertis文件
* @return 返回PropertiesReader的实例
*/
public static PropertiesReader getIntance() {
if (instance == null)
instance = new PropertiesReader("/struts.properties");
return instance;
}

/**
* 读取指定路径的properties文件
* @param path properties文件路径
* @return 返回PropertiesReader的实例
*/
public static PropertiesReader getIntance(String path) {
instance = new PropertiesReader(path);
return instance;
}

/**
* 根据资源名获取资源内容
* @param {String} key 资源文件内key
* @param {Stirng} defaultValue 默认值
* @reaurn String key对应的资源内容
*/
public String getProperty(String key, String defaultValue) {
if (Util.chgNull(key).equals(""))
return "";
return Util.chgNull(properties.getProperty(key, defaultValue));
}

private Properties createProperties(String path) {
Properties p = null;
Object obj = null;
try {
obj = getClass().getResourceAsStream(path);
if (obj == null)
obj = new FileInputStream(path);
} catch (IOException e) {
System.err.println("System can not find the property!");
}
if (obj != null) {
try {
p = new Properties();
p.load((InputStream) obj);
((InputStream) obj).close();
} catch (IOException e) {
p = null;
}
}
return p;
}

/**
* 通过输入的properties文件的key得到value
* @param key
* @return value
*/
public String getProperty(String key) {
if (Util.chgNull(key).equals(""))
return "";
return Util.chgNull(properties.getProperty(key));
}

public static void main(String[] args){
instance = new PropertiesReader("/struts.properties");
System.out.println(instance);
}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值