Java 从特定位置检索属性文件
如何从类路径加载位于Java 从特定位置检索属性文件,java,properties,classpath,Java,Properties,Classpath,如何从类路径加载位于src/main/resources/utility下的属性文件 Properties prop = new Properties(); try { // load a properties file prop.load(new FileInputStream("src/main/resources/utility/config.properties")); // get the property value and print it out
src/main/resources/utility
下的属性文件
Properties prop = new Properties();
try {
// load a properties file
prop.load(new FileInputStream("src/main/resources/utility/config.properties"));
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
}
从getResourceAsStream检索的示例将定位相对于类路径“根”的文件 initFile-文件位置: init文件也可以打包为war的一部分
Properties props = new Properties();
InputStream uin = this.getClass().getResourceAsStream(initFile);
InputStreamReader isr = new InputStreamReader(uin);
BufferedReader in = new BufferedReader(new InputStreamReader(uin));
props.load(uin);
通常,在编译时引用
src/
文件夹是个坏主意,但绝不是在运行时。相反,使用实用程序/config.properties
,因为这与运行时类路径相匹配。事实上,您误导了该节,是第3节带有类路径中的属性文件,更正确的方法是prop.load(App.class.getClassLoader().getResourceAsStream(“config.properties”)代码>,但非常感谢!