properties配置文件读取工具类

properties配置文件读取工具类

    本文中将首先介绍一下读取properties配置文件的几种方式,然后详细介绍基于java.util.ResourceBundle的propertiesUtil工具类写法。

一、Java读取properties配置文件的方法,总的来说有3种:

1、基于ClassLoder读取配置文件

Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");
// 使用properties对象加载输入流
properties.load(in);
//获取key对应的value值
properties.getProperty(String key);

注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。

2、基于 InputStream 读取配置文件

Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/config.properties"));
properties.load(bufferedReader);
// 获取key对应的value值
properties.getProperty(String key);

注意:该方式的优点在于可以读取任意路径下的配置文件

3、通过 java.util.ResourceBundle 类来读取

1>通过 ResourceBundle.getBundle() 静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可

properties.getProperty(String key);
//config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可  
ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");
String key = resource.getString("keyWord"); 

2>从 InputStream 中读取,获取 InputStream 的方法和上面一样。

ResourceBundle resource = new PropertyResourceBundle(inStream);

注意:这种方式比使用 Properties 要方便一些,获取properties属性文件不需要加.properties后缀名,只需要文件名即可。

总结:在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件在当前类所在的包下,那么需要使用包名限定,如:config.properties入在com.test.config包下,则要使用com/test/config/config.properties(通过Properties来获取)或com/test/config/config(通过ResourceBundle来获取);属性文件在src根目录下,则直接使用config.properties或config即可。

二、基于java.util.ResourceBundle 类来读取properties配置文件的工具类

java.util.ResourceBundle类如何使用,上面已做了简单的介绍,在此及直接上代码了:

package com.wonddream.utils;

import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Parsing The Configuration File
 * 
 */
public final class PropertiesUtil {
	private static Log log = LogFactory.getLog(PropertiesUtil.class);
	
	/**
	 * 根据配置文件路径和key,获取配置参数
	 * @param key
	 * @param configPath
	 * @return
	 */
	public static String getString(String key,String configPath) {
        //如果配置文件唯一,可以在类中把configPath成名为常量,把ResourceBundle对象声明为全局静态变量
		ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(configPath);
		try {
			return RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			log.error("getString", e);
			return null;
		}
	}

	/**
	 * 根据配置文件路径和key,获取配置参数(整型)
	 * @param key
	 * @param configPath
	 * @return
	 */
	public static int getInt(String key,String configPath) {
		return Integer.parseInt(getString(key,configPath));
	}
	
	/*
	 * 测试
	 */
	public static void main(String[] args) {
		System.out.println(getString("redis.address","config/redisConfig"));
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42315600/article/details/87170735