Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileNotFoundException on linux machine when using getClassLoader().getResource

Tags:

java

linux

I made already quite some research on internet for this problem. I had no luck so far. Basically this piece of code works fine on Windows with my Junit test src\test\java\com\project\utils\MyTestCase.java :

URL urlApplicationContext = this.getClass().getClassLoader().getResource("applicationContext.xml");
final String[] paths = { urlApplicationContext.getFile()};
ApplicationContext ctx = new FileSystemXmlApplicationContext(paths);

This file is located there:

\src\test\resources\applicationContext.xml

However on the Jenkins machine which run on linux I got the following error :

testSimple(com.project.ClientImplTest): IOException parsing XML document from file [/data/continuous/workspace/sonar/main_proj/data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml]; nested exception is java.io.FileNotFoundException: data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml (No such file or directory)

I already verified that the file /data/continuous/workspace/sonar/main_proj/target/main/WEB-INF/test-classes/applicationContext.xml does exist.

Why the getResource() does not find the correct path on Linux. It seems it finds data/continous/... instead of /data/continous/... for some reason ? Therefore FileSystemXmlApplicationContext may return an exception because it cannot find the file.

Thanks

like image 998
Jean Reno Avatar asked May 13 '26 00:05

Jean Reno


2 Answers

I had the same problem in my project - it was caused by spaces in the path - to handle such cases, you need to use the URL's toURI() method - do following:

ApplicationContext ctx;
URL urlApplicationContext = this.getClass().getClassLoader().getResource("applicationContext.xml");
if (urlApplicationContext != null) {
    File appCtxFile = new File(urlApplicationContext.toURI());
    ctx = new FileSystemXmlApplicationContext(new String[]{ appCtxFile.getAbsolutePath() });
} else {
    throw new RuntimeException("Cannot find XML file 'applicationContext.xml'");
}
like image 99
Oifan Avatar answered May 14 '26 15:05

Oifan


Try to add some debug output. URL has nice toString() method. Thus you'll get where app is looking for file.

It looks like you missed slash at the very beginning. Replace data/continuous/... to /data/continuous/... in your resource loader.

like image 32
Sergey Fedorov Avatar answered May 14 '26 14:05

Sergey Fedorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!