java获取properties文件

maven依赖

<dependency>
	<groupId>commons-configuration</groupId>
	<artifactId>commons-configuration</artifactId>
	<version>1.10</version>
	<scope>compile</scope>
</dependency>
package com.yt.eos.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.configuration.reloading.ReloadingStrategy;

/**
 * properties文件获取类
 * @author tyg
 * @date   2018年11月2日下午6:27:26
 */
public class PropertiesConfig {

	/**
	 * 获取配置文件类(这个是java自带的)
	 * @param fileName	文件名称
	 * @return
	 * @throws IOException
	 * @return Properties
	 * @author tyg
	 * @date   2018年11月2日下午6:28:59
	 */
	public static Properties getProperties(String fileName) {
		Properties properties = new Properties();
		try {
			properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return properties;
	}
	
	/**
	 * 这个可以直接获取对应的值的类型,如:config.getBigdecimal();
	 * @param fileName
	 * @return
	 * @return PropertiesConfiguration
	 * @author tyg
	 * @date   2018年11月2日下午6:39:27
	 */
	public static PropertiesConfiguration getPropertiesForApache(String fileName) {
		PropertiesConfiguration config = new PropertiesConfiguration();
		InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
		BufferedReader bf = new BufferedReader(new InputStreamReader(is));
		ReloadingStrategy r = new FileChangedReloadingStrategy();
		config.setReloadingStrategy(r);
		try {
			config.load(bf);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		} finally {
			if (bf != null) {
				try {
					bf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return config;
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_26365837/article/details/89926751