读取属性文件

时间:2013-03-10 09:41:47

标签: java maven

我创建了一个REST Web服务,其中我创建了一个config.properties文件来存储和检索整个应用程序中的一些用户名和密码。我将它存储在/src/main/resources/config.properties中。

当我尝试从eclipse的java代码中加载它时它运行正常。但是当我在tomcat中部署它时,它没有加载。我用来加载属性文件的代码是

properties.load(new FileInputStream("src/main/resources/config.properties"));

任何人都可以帮我解决这个问题吗

3 个答案:

答案 0 :(得分:2)

如果属性文件位于WEB-INF / classes中,则可以轻松完成。在这种情况下,只需编写类似

的内容
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/name.properties"));

显然,该文件可能位于类的子文件夹中。在这种情况下,您必须在调用getResourceAsStream()

时指定完整路径

答案 1 :(得分:1)

尝试从类路径加载它: -

final Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("/config.properties"));

答案 2 :(得分:1)

假设您想在运行时读取位于/WEB-INF/props/example.properties中的example.properties文件。

    Properties properties = new java.util.Properties();  
        InputStream inputStream =     
            getServletContext().getResourceAsStream("/WEB-INF/props/example.properties");  
properties.load(inputStream);  

现在,我们已准备好从example.properties文件获取值。

String value = properties.getProperty("propertyName");

示例属性文件:

example.properties

propertyName = 123

相关问题