如何在Java命令行选项中将资源文件夹添加到类路径 [英] How to add resource folder to classpath in Java command line options

查看:47
本文介绍了如何在Java命令行选项中将资源文件夹添加到类路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从命令行运行Junit测试用例.

I am trying to run Junit test cases from command line.

我从Windows系统中的文件夹 D:\ WorkSpace \ Testspace \ MyProject \ target 触发测试,如下所示:

I fire my tests in windows system from a folder D:\WorkSpace\Testspace\MyProject\target like this :

java -cp "classes;junit;dependency\*"  org.junit.runner.JUnitCore com.abc.TestA

这是一个Maven项目.它将引发以下错误:

This is a maven project. It throws the following error :

2019-07-09T17:59:41.330 ERROR [com.abc.IOUtil] - FileNotFoundException Occurredjava.io.FileNotFoundException: D:\WorkSpace\Testspace\MyProject\target\cde\FGH\SomeRandomFile.xml (The system cannot find the path specified)IOUtil

这个包含xmls的 cde 文件夹也位于 target 文件夹中,我从该文件夹中触发测试命令.

This cde folder containing the xmls is also inside the target folder from which I am firing my test commands.

是否可以在Java命令行中包含资源文件?

Is there any way to include the resource files in java command line?

推荐答案

在您的源代码中,使用以下构造:

In your source code, use the following construct:

package com.foo.package;

public class Example {
    public void loadResourceExample) {
         Example.class.getResource("/cde/FGH/SomeRandomFile.xml");
         Example.class.getResource("relative/example.xml");
    }
}

第一行将从类路径中提到的任何文件夹或jar中加载资源"/cde/FGH/SomeRandomFile.xml",因此在示例命令行中, D:\ WorkSpace \ Testspace \ MyProject \ target \例如,可以扫描classes \ cde \ FGH \ SomeRandomFile.xml .

The first line will load resource "/cde/FGH/SomeRandomFile.xml" from any folder or jar mentioned in the classpath, so in your example command line, D:\WorkSpace\Testspace\MyProject\target\classes\cde\FGH\SomeRandomFile.xml would for example be scanned.

第二行考虑了您的类的包名称,因此,它将例如在 D:\ WorkSpace \ Testspace \ myProject \ dependency \ somedep.jar 中检查条目/com/foo/package/relative/example.xml.

The second line takes the package name of your class into account, so, it would for example check at D:\WorkSpace\Testspace\myProject\dependency\somedep.jar for entry /com/foo/package/relative/example.xml.

请注意,-cp参数中的*语法将采用指定文件夹中的每个 JAR 并将其包含在类路径中.这就是全部.

Note that the * syntax in the -cp parameter will take every JAR inside the stated folder and include it in the classpath. That's all it does.

如果您不使用 getResource ,则实际上取决于当前工作目录",并且-cp参数不会有任何作用.

If you are not using the getResource, you're dependent on the 'current working directory' which can be anything, really, and the -cp parameter wouldn't have any effect.

这篇关于如何在Java命令行选项中将资源文件夹添加到类路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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