11

我试图读取一个 .properties 文件并具有如下代码:

public final class Config  {
  static {
    Properties properties = new Properties();
    InputStream propertiesStream = Object.class.getResourceAsStream("config.properties");

    if (propertiesStream != null) {
      try {
        properties.load(propertiesStream);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      System.out.println("file not found");
    }
  }
}

但它一直说找不到文件。

属性的内容是

pwd=passw0rd

任何人都知道如何解决这个问题?

4

4 回答 4

23

它应该在类路径中,把它放到你的根源包中,如果它是一个 maven 项目把它放到src/main/resources目录中

于 2013-05-29T05:54:36.607 回答
0

您还可以将 config.properties 保存在与 Config.java 相同的文件夹中。

//InputStream propertiesStream = Object.class.getResourceAsStream("config.properties");
InputStream propertiesStream   = Config.class.getResourceAsStream("config.properties");
于 2013-05-29T06:13:35.487 回答
0

您可以有两种选择路径的选择,

  1. 打开包含文件夹的文件并获取路径并将该路径保存在带有文件的字符串中,例如,

    InputStream propertiesStream = Object.class.getResourceAsStream(path + File.seperator + "config.properties");

  2. 将文件保存在 src 路径中,

    WorkSpace -> 项目名称 -> Copyhere

于 2013-05-29T06:21:34.780 回答
0

它应该在WebContent/Web-Inf/文件夹中

并在您的 xml 文件中定义 bean,如下所示:

<bean id="propertyConfigurer" class="com.your.project.util.properties.ApplicationProperties">
    <property name="locations">
        <list>
            <value>/WEB-INF/application.properties</value>
        </list>
    </property>
</bean>
于 2013-05-29T05:59:03.903 回答