【问题标题】:Where to put a properties file?在哪里放置属性文件?
【发布时间】:2023-07-25 18:06:01
【问题描述】:

我尝试读取一个 .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

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: java properties myeclipse


    【解决方案1】:

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

    【讨论】:

    • 但是更改将需要编译。如果我们改为使用固定路径怎么办?但是如果找不到路径,缺点将是错误。哪个更好?
    【解决方案2】:

    它应该在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>
    

    【讨论】:

    • 如果你使用的框架是Spring,那么这个可以正常工作
    • OP说他用的是spring吗?
    • 我后来意识到,出于同样的原因,我已经发表了评论(在你之前),并添加了免责声明。对于在使用 Spring 并面临同样问题时偶然发现这个问题的人来说,这可能会有所帮助。
    【解决方案3】:

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

    //InputStream propertiesStream = Object.class.getResourceAsStream("config.properties");
    InputStream propertiesStream   = Config.class.getResourceAsStream("config.properties");
    

    【讨论】:

      【解决方案4】:

      路径选择有两种选择,

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

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

      2. 将文件保存到src路径,

        WorkSpace -> 项目名称 -> Copyhere

      【讨论】: