MSS
MSS

Reputation: 3623

How to add resource folder to classpath in Java command line options

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

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

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

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

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

Upvotes: 3

Views: 4377

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102872

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");
    }
}

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.

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.

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.

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.

Upvotes: 1

Related Questions