Java:如何从不同的模块中读取文件? [英] Java: How to read file from different module?

查看:1115
本文介绍了Java:如何从不同的模块中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个maven模块的项目

I have a project with multiple maven modules

project/pom.xml
       /external_services/pom.xml
                         /ifs/pom.xml
                             /src/test/java/
                                           /MockIFSClient.java
                                           /IFSClientTest.java
                             /src/test/java/resources/sample.json
       /inventory/pom.xml
                 /business/pom.xml
                             /src/main/java/InventorySummary.java
                 /services/pom.xml
                             /src/main/java/InventorySummaryResource.java
                             /src/main/test/InventorySummaryResourceTest.java

MockIFSClient 访问 sample.json as

try {
    inventoryPriceDetails = mapper.readValue(new File(getClass().getResource("/getInventoryAndPriceResponse.json").getPath()), new TypeReference<List<InventoryPriceDetail>>() {
    });
} catch (final IOException e) {
    throw new RuntimeException("could not read resource :" + e.getMessage());
}

所以 IFSClientTest 运行鳍,因为它们是相同的包。

so IFSClientTest runs fins since they are in same package.

问题?

InventorySummaryResourceTest 来电 MockIFSClient 试图访问相同的代码,但现在它失败了

Problem?
InventorySummaryResourceTest calls MockIFSClient which tries to access the same code, but now it fails as

could not read resource :file:/Users/harith/IdeaProjects/inventory_api/external_services/ifs/target/ifs-1.0-SNAPSHOT-tests.jar!/sample.json (No such file or directory)

services / pom.xml 依赖为

<dependency>
    <groupId>com.org.project.external_services</groupId>
    <artifactId>ifs</artifactId>
    <version>${project.version}</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>

问题

我对

new File(getClass().getResource("/getInventoryAndPriceResponse.json").getPath())

以便可以从不同的模块访问

so that it can be accessed from different modules as well

推荐答案

这个答案帮助我做对了

如何真正从Java中的classpath读取文本文件

我将代码更改为

inventoryPriceDetails = mapper.readValue(getClass().getResourceAsStream("/getInventoryAndPriceResponse.json"), new TypeReference<List<InventoryPriceDetail>>() {});

这篇关于Java:如何从不同的模块中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆