读取属性文件
我创建了一个REST Web服务,其中我创建了一个config.properties文件,用于存储和检索整个应用程序中的一些用户名和密码。 我将它存储在/src/main/resources/config.properties中。
当我试图从我的java代码中加载它时,它的工作正常。 但是当我在tomcat中部署它时,它没有加载。 我用来加载属性文件的代码是
properties.load(new FileInputStream("src/main/resources/config.properties"));
任何人都可以帮我解决这个问题
您部署到Tomcat的是war文件。 Tomcat不知道或不关心应用程序源的目录。
src/main/resources
中的文件由Maven复制到target/classes
目录,然后将此目录复制到已部署的Web应用程序的WEB-INF/classes
目录中,该目录位于webapp的类路径中。 所以你只需要使用类加载器加载文件:
properties.load(MyClass.class.getResourceAsStream("/config.properties"));
(MyClass是您的webapp的任何类)。
如果属性文件位于WEB-INF / classes中,则可以轻松完成。 在这种情况下,只需写一些东西
Properties props = new Properties(); props.load(getClass().getResourceAsStream("/name.properties"));
显然,该文件可能位于类的子文件夹中。 在这种情况下,您必须在调用getResourceAsStream()时指定完整路径
尝试从类路径加载它: –
final Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/config.properties"));
假设您要在运行时读取位于/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