application.properties文件的相对路径是什么?

时间:2015-03-05 21:48:14

标签: java java-ee

enter image description here

需要在LoadProperties.java文件中加载

application.properties。

public static属性loadProperties(){

    Properties props = new Properties();
    try{
        FileInputStream fis = new FileInputStream("application.properties");
        props.load(fis);    
        fis.close();
    }catch(IOException ioe){
        ioe.printStackTrace();
    }
    return props;
}

以上代码在普通Java Project中运行正常,但是当我在动态Web项目路径中添加此代码时,由于文件夹结构不同而无法识别

我试过很多方法并得到了java.io.FileNotFoundException:application.properties(系统找不到指定的文件)错误

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

Properties props = new Properties();

//with properties in the root dir 
props.load(getClass().getResourceAsStream("/application.properties"));

答案 1 :(得分:0)

使用classloader:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("your.properties").getFile());

在流中使用classloader:

ClassLoader classLoader = getClass().getClassLoader();
InputStream in = classLoader.getResourceAsStream("your.properties");

使用ResourceBundle:

ResourceBundle labels = ResourceBundle.getBundle("your.properties", locale);
System.out.println(labels.getString("label1"));

答案 2 :(得分:0)

如果我在eclipse安装时添加文件并给出如下所示的路径它对我来说很好。

FileInputStream fis = new FileInputStream(“application.properties”);

enter image description here