如何从 Maven 依赖项目中读取文件?

DP_*_*DP_ 1 java maven

我有两个Maven项目A和B。B依赖于A。

someFile.txt在A中,我的文件夹中有一个文件src/main/resources

public class SomeAClass
{
    public void someMethod()
    {
        final InputStream inputStream =
                Thread.currentThread()
                        .getContextClassLoader()
                        .getResourceAsStream("someFile.txt");
        final List<String> lines = IOUtils.readLines(inputStream);

        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在 A 的测试中,这工作得很好。

现在假设我想在 B 中使用相同的代码,包括从src/main/resources/someFile.txt.

现在,SomeAClass.someMethod()从项目 B 调用会导致 NullPointerException,我怀疑这是因为src/main/resources/someFile.txt找不到。

如何更改获取输入流的代码,src/main/resources/someFile.txt以便它在 A 的单元测试和执行 B 时都有效(B 是基于 Spring Shell 的控制台应用程序)?

Ike*_*ayo 5

您确定问题存在吗,因为我有类似的方法并且它工作正常。

那是我的第一次尝试

如果您在测试中使用 someFile.txt 作为资源(并且仅在那里,如果您在主项目中使用,请忽略该帖子),而不是使用src/main/resources,也许最好放置该文件和其他使用的文件在src/test/resources

如果将这些测试文件放入 中src/test/resources,请记住测试资源不包含在项目工件中,因此即使您在 pom.xml 中包含依赖项,也无法访问它们。

我做了什么(和你一样)

创建新模块(测试资源)并将资源放入src/main/resources. 该模块用作我需要测试范围的项目中的依赖项。但我使用的是ClassPathResource。

    ClassPathResource resource = new ClassPathResource("the_file"); 
    resource.getInputStream()
Run Code Online (Sandbox Code Playgroud)