有时候我们需要将程序打Jar包,为了方便维护配置文件,一般情况下不会将配置文件直接打包到Jar文件里,而是放到Jar包之外的本地目录下,因此程序运行时需要读取外部某conf forder 下的config.properties 配置文件,可以使用以下方法。
public static void main(String[] args) {
try {
Properties prop = new Properties();
// 获取外部配置文件Path: System.getProperty("user.dir")
String confPath = System.getProperty("user.dir") + "\\conf\\config.properties";
File fileTemp = new File(confPath);
InputStream in = new FileInputStream(fileTemp);
prop.load(in);
logger.info("Loading the sys_config.properties");
//获取properties 文件里的name为SourceFileDirectory的value
String sourceFileDirectory = prop.getProperty("SourceFileDirectory").trim();
logger.info("The source file directory is " + sourceFileDirectory);
} catch (IOException e) {
e.printStackTrace();
}
}
注意:当程序拿到配置文件Path后,需要将其new File后转换成inputStream 供Properties对象使用。如果是内部的配置文件,则不需要多此一举,可以通过Java中的getResourceAsStream直接转换成inputStream,
Eg:InputStream in = Object.class.getResourceAsStream("../conf/config.properties")
但如果是外部配置文件,即便正确获取到配置文件所在Path,依然无法使用getResourceAsStream将其转化成InputStream。