简体   繁体   中英

ClassLoader.getResource returning null while using File.getAbsolutePath

I have a config.ini file I need to open that is quite far back in directory so I used File.getAbsolutePath() to set the base directory and concatenated the remainder of the path.

Printing the path, I get the correct path that I can paste into file explorer, but the object returned is null.

So I started by initializing my Properties and ClassLoader as such:

Properties prop = new Properties();
ClassLoader classLoader = Test.class.getClassLoader();

Then I create the path. I tried escaping a back slash(1) as well as forward slash(2), both return null but both paths work in file explorer.

String absPath = new File("").getAbsolutePath();
absPath = absPath.concat("\\resources\\config\\config.ini"); // (1)
absPath = absPath.concat("/resources/config/config.ini"); // (2)

then I try to set the URL to open an InputStream

URL res = Objects.requireNonNull(classLoader.getResource(absPath), "Unable to open config.ini");
InputStream is = new FileInputStream(res.getFile());

However, the following returns null.

classLoader.getResource(absPath)

I expected this to properly open the file because the path was correct. I am using Intelij and I read that I needed to add the .ini resource file under settings > compiler, which I did but that did not resolve my issue.

Thank you!

That's not the way to load resources via class-loaders.

If your classpath is something like the following ...

java -cp resources;lib/my.jar ... org.mypack.MyClass

then you load it with this path

getClassLoader().getResource("/config/config.ini");

Your classpath includes the resources folder, and the class-loader loads from there.

The absolute path of the OS is quite certainly not in classpath.

In any case, you must be certain that the resource folder is in classpath.

If your config file is not in classpath then you can't use classloaders to load that file.

Just one more thing, if your configuration is not in classpath, but in a child directory of your working dir, why can't you simply use new FileInputStream("resources/config/config.ini");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM