Search code examples
javafilejarclassloader

how to find a local resource from dependent jar?


I have written a code that is packed to 1.jar

with this code:

    return isProd? "/etc/waze/automation/devices.json":
            DeviceRepositoryFromJsonFile.class.getClassLoader().getResource("devices.json").getPath().toString();

devices.json is here:

enter image description here

I have another project that depends on 1.jar

however the classLoader doesn't find the local devices.json file but rather one packed in the jar

anyhow it shows the file doesn't exist.

enter image description here

How can I fix this? just use a absolute path anyhow?


Solution

  • If as in your screenshot the devices.json locate in the src/main/resources and the package have successfully treat that as the package path and put in the jar file root directory, then you can just find the file via:

    DeviceRepositoryFromJsonFile.class.getResource("/devices.json");
    

    Note the "/" slash is important to indicate that to search from the root of the classpath.