Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从特定位置检索属性文件_Java_Properties_Classpath - Fatal编程技术网

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”),但非常感谢!