Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ClassLoader getResource with special characters in path

Tags:

java

I have the following problem. In our integration tests we use a different config which will be loaded from test resources with the following code prior to the tests:

URL resource = ClassLoader.getSystemResource("application.conf");

This works fine as long as there are no special characters in path. For example having the following correct path

D:/Dev/projects/#FLI/flinsta/fgraph/build/resources/test/application.conf

will result in the following wrong file path given by getSystemResource:

D:/Dev/projects/%23FLI/flinsta/fgraph/build/resources/test/application.conf

This then results in a file which simply doesn't exist. How can I make sure that something like this does not happen. Renaming the path is an option. However I would like to find a solution instead of a workaround.

Thank you for any help!

like image 576
Julian Pieles Avatar asked Aug 27 '15 13:08

Julian Pieles


People also ask

What is the difference between Class getResource () and Classloader getResource ()?

Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.

How to read text file in java from resource folder?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().

How to access resources java?

Java programs can use two mechanisms to access resources: Applets use Applet. getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet. getAudioClip(url) .


1 Answers

To answer my own question with the help of the comments:

URL resource = ClassLoader.getSystemResource("application.conf");
String configPath = URLDecoder.decode(resource.getFile(), "UTF-8");

Variable configPath then contains the correct path.

like image 91
Julian Pieles Avatar answered Sep 16 '22 13:09

Julian Pieles