【问题标题】:Maven dependency cannot find its resourcesMaven依赖找不到它的资源
【发布时间】:2012-09-18 11:09:24
【问题描述】:

我在 Netbeans 中有两个 Maven 项目,com.foo.bar 和 com.foo.baz。

com.foo.bar 是 com.foo.baz 的依赖项。

bar
+-src
| +-main
|   +-java
|   | +-com
|   |   +-foo
|   |     +-bar
|   |       +-App.java
|   +-resources
|     +-com
|       +-foo
|         +-bar
|           +-config.properties
+-target
| +-classes
|   +-com
|     +-foo
|       +-bar
|         +-App.class
|         +-config.properties
+-pom.xml

当我在 Netbeans 中单击以展开项目 baz->dependencies->bar->com.foo.bar 时,我看到的内容与 bar/target/classes/com/foo/bar 相同。我认为一切都很好。

com.foo.bar 有线条

// print current directory
System.out.println(new File(".").getAbsolutePath());

// load config files
Properties conf = new Properties();
conf.load(new FileInputStream(config.properties));

com.foo.baz 类似,但在 resources/ 中没有任何内容。当我构建依赖关系 com.foo.bar 和 com.foo.baz 然后运行 ​​com.foo.baz 时,我得到 ​​p>

/home/user/NetBeansProjects/baz/.
java.io.FileNotFoundException: config.properties (No such file or directory)

这是类路径的问题,还是什么? Maven 不应该处理这个吗?

【问题讨论】:

  • 尝试使用 getClass().getResourceAsStream("com/foo/bar/config.prioperties")

标签: maven dependencies classpath


【解决方案1】:

你需要将整个路径添加到文件中,像这样

conf.load(new FileInputStream("com/foo/bar/config.properties"));

如果您将文件放在资源内的根文件夹中,它可以在没有路径的情况下工作。

bar
+-src
| +-main
|   +-java
|   | +-com
|   |   +-foo
|   |     +-bar
|   |       +-App.java
|   +-resources
|       +-config.properties
(...)

【讨论】:

    【解决方案2】:

    如果你想从App 类中加载config.properties,那么你可以这样做:

    public class App {
    
        public void someMethod() {
            InputStream is = getClass().getResourceAsStream("config.properties");
            Properties properties = new Properties();
            try {
                properties.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("foo = " + properties.getProperty("foo"));
        }
    
        public static void main(String[] args) {
            App app = new App();
            app.someMethod();
        }
    }
    

    config.properties 相对于与getResourceAsStream() 一起使用的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 2011-11-18
      • 2016-10-01
      • 2020-04-18
      • 2013-05-07
      • 2011-12-26
      • 1970-01-01
      相关资源
      最近更新 更多