【问题标题】:FileNotFoundException with properties file带有属性文件的 FileNotFoundException
【发布时间】:2014-01-28 18:32:55
【问题描述】:

我正在尝试从backupData.properties 读取一些道具。它位于WEB-INF/classes/。我就是这样做的:

public class Configures {

    private static final String INPUT_FILE = "WEB-INF//classes//backupData.properties"; 


    public static String getMail() {
        Properties prop = new Properties();
        try {
            //load a properties file
            prop.load(new FileInputStream(INPUT_FILE));

            //get the property value
            return prop.getProperty("mail");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

INPUT_FILE 应该包含什么?我试图把它放在src 中,比如src//backupData.properties,但它会抛出FileNotFoundException。我用谷歌搜索该文件应该位于CLASSPATH(据我所知在WEB-INF/classes)。怎么了?

PS。我正在使用 Spring。

【问题讨论】:

  • 你检查绝对路径吗??

标签: java spring-mvc properties


【解决方案1】:

这与 Spring 无关。如果您正在部署 Web 应用程序,WEB-INF/classes 中的所有内容都将从类路径的根目录开始出现。

您可以通过

InputStream 获取到该资源
InputStream in = Configures.class.getResourceAsStream("/backupData.properties");
prop.load(in);

由于 Web 应用程序并不总是从其 .war 文件中提取,因此实际的属性文件可能仅作为 zip 条目存在。因此,您不能(也不应该)使用FileInputStream 检索它。

Here's the javadoc.

【讨论】:

  • 我不认为你想要名称中的斜线。
  • @jalynn2 你为什么不这么认为?
  • 因为它在类路径的根目录中?
  • @jalynn2 出于这个特定原因,它需要有领先的/。否则,它将相对于 Configures 所在的包进行解析。
  • @Tony 不客气。查看我链接的 javadoc 并尝试熟悉类路径。在这方面,网络应用与独立应用略有不同。
【解决方案2】:

由于您使用的是 SPRING ,我建议您“可以”将其用作 Bean 定义的一部分:

<property name="template" value="classpath:/backupData.properties">

Resource template = ctx.getResource("classpath:/backupData.properties");

@Sotirios Delimanolis建议的普通旧

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2012-10-27
    • 2013-05-13
    • 1970-01-01
    相关资源
    最近更新 更多