gpt4 book ai didi

Java:如何从资源文件夹加载 .properties?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:12:54 31 4
gpt4 key购买 nike

我在 IntelijWorkspace 中有一个 Manven 项目,在 /resources 文件夹中,我添加了一个名为 SBMessages.properties.properties 文件。现在,我试图从 Java 获取这个文件,它总是抛出 FileNotFoundException。 下面是我的项目树:

enter image description here

以及我在 SBConnector.class 中获取 .properties 文件的代码:

public void initialize() {
SBMessages = new Properties();
try {
SBMessages.load(getClass().getResourceAsStream("/sb/elements/SBMessages.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

尝试调试,路径直接到/target/classes/elements/SBMessages.properties而不是/resources/sb/elements/SBMessages.properties.

请帮我解决这个问题。

最佳答案

不同的框架提供不同的类加载器。您可能拥有来自您正在使用的 JRE 的“默认”类加载器。它将遵循 JDK 文档。您可能会遇到此页面: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)但更有用的页面是这个: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)这实际上是说您可以使用斜线开始您的资源名称。

尽管有此文档,您的类加载器可能并未遵循这些规则。多么令人失望。因此,可以尝试三种形式:

  1. 绝对以斜杠开头。
  2. 没有开始斜杠的绝对值。
  3. 没有任何斜线的亲戚。

除了这三种形式之外,您还必须在正确的类上调用 getResourceAsStream()。该类应该与保存您的属性文件的文件位于同一个 jar 文件中。这可能会造成混淆,所以从一个简单的示例开始是件好事。 :-)

像这样为我工作:

public static void main(String[] args) {
new NewMain().doit();
}

public void doit() {
Properties prop = new Properties();
try (InputStream inputStream = NewMain.class.getResourceAsStream("/data/newproperties.properties")) {

prop.load(inputStream);
System.out.println("hello " + prop.getProperty("x", "default"));

} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
} catch (IOException e) {
e.printStackTrace(System.out);
}

}

关于Java:如何从资源文件夹加载 .properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889083/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com