【问题标题】:jar resource loads in test but not in application [duplicate]jar资源在测试中加载但不在应用程序中[重复]
【发布时间】:2014-02-28 15:00:05
【问题描述】:

我有一个构建 xmlreader 类的 maven 项目,该类具有 2 个构造函数。一种采用外部文件名,另一种采用默认加载资源。

默认构造函数用于测试,但当我使用默认参数执行程序时找不到文件。更改我访问资源的方式会使测试失败并且 maven 停止构建。我已经提取了 jar,文件就在里面。

这里是构造函数:

public XmlReader() {
    this.filename = getClass().getResource("/Default.xml").getPath();
    this.git = new GitClass();
    this.cucumber = new CucumberClass();
    this.execute = new ExecuteClass();
}

错误信息:

5030 [main] ERROR - File file:/Users/andreasjoelsson/XmlReader/target/XmlReader-1.0-SNAPSHOT.jar!/Default.xml not found.
5030 [main] DEBUG - Context: init of reader: false

JUnit 测试:

@Test
public void test2() {
    XmlReader testObject = new XmlReader();
    // Subject to change as it's the default config to run.
    assertEquals(true, testObject.init());
    assertEquals(25, testObject.getExecute().getMaxUsers());
    assertEquals(true, testObject.getExecute().isRepeatFeature());
    assertEquals(1, testObject.getExecute().getSecondsBetweenIncrease());
    assertEquals(2, testObject.getExecute().getUsersIncreasedEachInterval());
    assertEquals(20, testObject.getExecute().getWaitAfterRampSeconds());
    System.out.println(testObject.toString());
}

所以我执行测试的包可以工作,但当我在 maven 之外运行它时却不行。

【问题讨论】:

标签: java maven junit jar


【解决方案1】:

当您将它们作为硬盘文件系统的一部分使用时,您无法使用 JAR 中的文件。

在开发过程中,您拥有工作区中的所有源文件。所以文件系统中确实存在物理文件。 new File(fileName)getResource(resourceName).getPath() 之类的语句可以正常工作。

在处理 JAR 中的资源时,首先必须通过Class.getResource(resourceName)ClassLoader.getResource(resourceName) 检索资源。您将获得一个没有文件协议的 URL,这也是您无法在其上调用 getPath() 的原因。您必须使用URL.openStream() 检索输入流。有了它,您可以读取您的资源(并且不要忘记之后关闭流)。

【讨论】:

  • 在使用流时效果很好。这是相当奇怪的失败,因为我认为程序可以像普通文件系统一样访问 jar 中的文件。
【解决方案2】:

您需要在项目中创建一个名为 src 但名称不同的源文件夹。 要在 Windows 上引用此文件夹中的文件,您只需指明项目名称和资源名称即可:

getResource("ProjectName/Default.xml")

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    相关资源
    最近更新 更多