Java 从类路径获取文件,以便测试可以在所有计算机上运行

Java 从类路径获取文件,以便测试可以在所有计算机上运行,java,vert.x,Java,Vert.x,我正在使用Vertx并尝试测试一些参数,我从jsonfile获取数据,目前它可以工作,但我希望通过类路径获取此文件,以便可以从其他计算机上测试它 private ConfigRetriever getConfigRetriever() { ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setOptional(true) .setConfig(new JsonObjec

我正在使用Vertx并尝试测试一些参数,我从jsonfile获取数据,目前它可以工作,但我希望通过类路径获取此文件,以便可以从其他计算机上测试它

private ConfigRetriever getConfigRetriever() {
    ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setOptional(true)
            .setConfig(new JsonObject()
                .put("path", "/home/user/MyProjects/MicroserviceBoilerPlate/src/test/resources/local_file.json"));
    ConfigStoreOptions sysPropsStore = new ConfigStoreOptions().setType("sys");
    ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore).addStore(sysPropsStore);
    return ConfigRetriever.create(Vertx.vertx(), options);
}
如上所述,我的路径从/home/dir开始,这使得它不可能在另一台机器上进行测试。我下面的测试使用这个配置

@Test
public void tourTypes() {
    ConfigRetriever retriever = getConfigRetriever();

    retriever.getConfig(ar -> {
        if (ar.failed()) {
            // Failed to retrieve the configuration
        } else {
            JsonObject config = ar.result();

            List<String> extractedIds = YubiParserServiceCustomImplTest.getQueryParameters(config, "tourTypes");
            assertEquals(asList("1", "2", "3", "6"), extractedIds);
        }
    });
}

将.json文件放入项目()的
/resources
文件夹中。 然后通过以下方式访问:


将.json文件放入项目()的
/resources
文件夹中。 然后通过以下方式访问:


如果您已将文件存储在
“src/test/resources”
中,则可以使用

InputStream confFile=getClass().getResourceAsStream(“/local_file.json”)

URL=getClass().getResource(“/local_file.json”)

在测试类()中

重要!
在这两种情况下,文件名都可以以/或不以开头。如果是,则从类路径的根开始。如果不是,则从调用该方法的类的包开始。

如果您已将文件存储在
“src/test/resources”
中,则可以使用

InputStream confFile=getClass().getResourceAsStream(“/local_file.json”)

URL=getClass().getResource(“/local_file.json”)

在测试类()中

重要!
在这两种情况下,文件名都可以以/或不以开头。如果是,则从类路径的根开始。如果不是,则从调用该方法的类的包开始。

据我所知,考虑到json文件的位置,您只需执行以下操作:

.setConfig(new JsonObject().put("path", "local_file.json"));

请参阅以供参考。

据我所知,考虑到json文件的位置,您只需执行以下操作:

.setConfig(new JsonObject().put("path", "local_file.json"));

请参阅以获取参考。

File resourcesFile=new文件(“src/test/resources/local_File.json”);我怎样才能将它添加到我的测试中并仍然访问它,因为我需要一个get配置,因为它是一个VERTXY。你可以将它放在'src/test/resources'或'src/main/resources'retriever.getConfig(ar->{if(ar.failed()){//failed to retrieve the configuration}else{JsonObject config=ar.result();我将无法访问该文件resourcesFile=new文件(“src/test/resources/local_File.json”);我如何才能将其添加到我的测试中并仍然访问它,因为我需要一个get config,因为它是一个vertxy,您可以将其放置在“src/test/resources”或“src/main/resources”retriever.getConfig(ar->{if(ar.failed()){//检索配置失败}否则{JsonObject config=ar.result();我将无法检索该配置
.setConfig(new JsonObject().put("path", "local_file.json"));