3

I'm using a file from resources dir, calling it using the code: XmlDataLoader.class.getClassLoader().getResource("testData").getPath()

It works well on my local machine and the path to the file is correct: C:/Work/PROJECT_NAME/test/selenium/target/classes/testData

Then I would like it to be used in Jenkins job on the server in linux environment but I get the NullPointerException:

[WARNING] File 'var/lib/jenkins/workspace/project/test/selenium/target/classes/testData/' does not exist

It is because there is a lost "workspace" directory between "project" and "test" folders in the path. The correct path should be: var/lib/jenkins/workspace/project/ws/test/selenium/target/classes/testData Required file is really exists there, but for some reason Jenkins build incorrect path, loosing the /ws/ directory. Can anyone give me a hand please? Why does class.getClassLoader().getResource("testData").getPath() doesnt work properly on the server?

I have resources set in Maven pom file:

<resource> <directory>resources</directory> </resource>

Bohdan Nesteruk
  • 794
  • 17
  • 42
  • is the ws there becouse it is a multiaxis project? – Srgrn Aug 27 '15 at 14:20
  • 1
    Not sure I'm with you, what does it mean - 'multiaxis project'? `ws` folder - it is project's Workspace, where all the files and folders are. As I can see, each project in Jenkind has it's own ws folder – Bohdan Nesteruk Aug 28 '15 at 06:35
  • what happens when you use the following `this.getClass().getResource("testData").getPath();` – rohit thomas Nov 11 '22 at 07:25

1 Answers1

0

Using .getResource("testData") can cause issues as you never know if the resource is even accessible.

At runtime, the resource folder is seldom in the same location on disk as it is in our source code. So we need another way of accessing the files.

Therefore the preferred way is to use getResourceAsStream(String) which returns an InputStream you can directly read from.

Best to load resources from the classpath instead of a specific file location:

try (InputStream inputStream = getClass().getResourceAsStream("/testData");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String contents = reader.lines()
  .collect(Collectors.joining(System.lineSeparator()));
}
Stempler
  • 1,309
  • 13
  • 25