- 將自身部分功能打成jar包時,需要動態從外部讀取配置文件。
- 此工具類優先從項目路徑下讀取配置文件,讀取不到時從classpath獲取配置文件。
- 使用方式:
- 開發時直接讀取項目資源目錄下的 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;
}
}
