jar包读取外部properties文件


  1. 将自身部分功能打成jar包时,需要动态从外部读取配置文件。
  2. 此工具类优先从项目路径下读取配置文件,读取不到时从classpath获取配置文件。
  3. 使用方式:
    • 开发时直接读取项目资源目录下的 properties即可
    • 打成jar包使用时,将配置文件与jar包放置在同一目录

代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtils {
	/**
	 * properties
	 */
	private static Properties properties = null;

	/**
	 * 根据key获取value值
	 * 
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		if (properties == null) {
			properties = loadConfProperties();
		}
		String value = properties.getProperty(key);
		System.out.println("从配置文件读取参数: " + key + " -->> " + value);
		return value;
	}

	/**
	 * 初始化propertiies
	 * 
	 * @return
	 */
	public static Properties loadConfProperties() {
		Properties properties = new Properties();
		InputStream in = null;

		// 优先从项目路径获取连接信息
		String confPath = System.getProperty("user.dir");
		confPath = confPath + File.separator + "conn.properties";
		File file = new File(confPath);
		if (file.exists()) {
			System.out.println("配置文件路径---->>" + confPath);
			try {
				in = new FileInputStream(new File(confPath));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 未传入路径时,读取classpath路径
		else {
			System.out.println("项目路径[" + confPath + "]下无连接信息,从classpath路径下加载");
			in = PropertiesUtils.class.getClassLoader().getResourceAsStream("conn.properties");
		}
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return properties;
	}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM