Java获取配置文件中的属性值通用类

项目中经常会遇到怎么去获取项目中配置文件的路径,或者是读取配置文件中的值。现在将方法记录下来,供大家学习参考。

1.读取配置文件中的属性值,这里的配置文件指的是conf.properties。如果大家有其他配置文件,记得把名字改下就可以了。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.log4j.Logger;

public class Configuration {
	private static final Logger log = Logger.getLogger(Configuration.class
			.getName());
	private static Properties p;
	static {
		p = new Properties();
		String path = getWebRoot() + File.separator + "WEB-INF"
				+ File.separator + "classes" 
				+File.separator+ "conf.properties";
		System.out.println(path);
		log.info("path:" + path);
		try {
			FileInputStream in = new FileInputStream(path);
			p.load(in);
			in.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static String getConfigValue(String name) {
		return p.getProperty(name);
	}

	@SuppressWarnings("unchecked")
	public static Enumeration<String> getConfigValuesEnum() {
		return (Enumeration<String>) p.propertyNames();
	}

	public static String getWebRoot() {
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		URL url = classLoader.getResource("/");
		String filepath = url.getPath();
		filepath = filepath.substring(0, filepath.lastIndexOf("/"));
		filepath = filepath.substring(0, filepath.lastIndexOf("/"));
		filepath = filepath.substring(0, filepath.lastIndexOf("/"));
		log.info("filepath------" + filepath);
		return filepath;
	}
}


2.获取配置文件的路径

最简单的方式通过request.getServletContext().getRealPath("/WEB-INF/conf.properties")来获取

request.getServletContext().getRealPath("/WEB-INF/conf.properties");




猜你喜欢

转载自blog.csdn.net/wangli61289/article/details/53691910