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