最近在一個項目,在項目下新建了一個config配置文件夾,添加一個配置文件config.properties.
使用classpath:config.properties方式加載配置文件,
具體實現代碼
String classpathKey = "classpath:";
Properties pt = new Properties();
String configPath = "classpath:config.properties";
try
{
InputStream inputStream = null;
if (configPath.startsWith(classpathKey)) {
inputStream =
this.getClass().getClassLoader().getResourceAsStream(configPath.substring(classpathKey.length()));
} else {
inputStream = new FileInputStream(configPath);
}
pt.load(inputStream);
configParams.putAll((Map) pt);
inputStream.close();
} catch(
Exception e)
{
logger.error("無法加載配置文件[{}]", new Object[]{configPath});
logger.error(e.getMessage(), e);
}
但是一直報錯誤“無法加載配置文件”。
仔細研究了一下Eclipse,原來是沒有把config加入到path中來
在Eclipse中設置:項目-》右鍵Build Path -》Configure Build Path.. -》 選擇Source下 Add Folder.. -》選中config -》OK
編譯運行,大功告成。
