Java中Properties文件读取工具类

本文介绍了一个用于读取属性文件的工具类PropertiesUtils,包括如何读取指定属性文件的内容及值,并提供了一种获取可复用属性文件对象的方法。

PropertiesUtils属性文件读取工具类

/**

 * 读取属性文件内容

 *

 */

public class PropertiesUtils {

public static final String OrgPropertiesName"baidu.properties";

public static final String ORG_ID "baidu_id";

public static final String ORG_NAME"baidu_name";


/**

* 读取属性文件中的值

* @param propertiesFileName 属性文件名称在classPath目录下

* @param key 属性文件中定义的key

* @return

* @throws IOException 

* @throws FileNotFoundException 

*/

public static String getValue(String propertiesFileName, String key) throws FileNotFoundException, IOException{

//通过文件名读取类路径下的属性文件

ClassPathResource cp = new ClassPathResource(propertiesFileName);

Properties props = new Properties();

//读取属性文件输入流

InputStream in = new BufferedInputStream(new FileInputStream(cp.getFile()));

//将输入流加载到属性对象中

props.load(in);

in.close();

//通过key在属性对象中读取值

return props.getProperty(key);

}

/**

* 获取属性文件对象,该对象可以重复使用,而不是每次都读取流操作

* @param propertiesFileName

* @return

* @throws FileNotFoundException

* @throws IOException

*/

public static Properties getProperties(String propertiesFileName) throws FileNotFoundException, IOException{

ClassPathResource cp = new ClassPathResource(propertiesFileName);

Properties props = new Properties();

InputStream in = new BufferedInputStream(new FileInputStream(cp.getFile()));

props.load(in);

in.close();

return props;

}

/**

* 通过属性文件对象获取value

* @param props 属性文件对象

* @param key 属性文件key

* @return

*/

public static String getValue(Properties props, String key){

return props.getProperty(key);

}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值