javajarresourcesorganizationgetresource

How to specify resource location in the same way when compiling TO and NOT TO a JAR file


I have a project that I am compiling using javac. I want to be able to fetch resources without having to first build my project into a JAR file, but at the same time, I don't want to hard code the location either (C://Users/name/etc).

I know that if I had a JAR file, I could use a ClassLoader and call one of the resource methods from there. Alternatively, if my resources were contained within another JAR file, and that JAR file was on my class path, then I could fetch it from the JAR file in a similar format.

But how do I do so when I am only compiling in javac? I don't want to have to rework all of my resource fetching logic when I eventually turn this into a JAR file, but I also don't want to have to make a jar file every time I compile and want to test a change. I just want to be able to specify to Java that this is where to find my resources, and I don't want to change that strategy when I finally decide to making a JAR file.


Solution

  • You can locate resources in the folder same way as in a jar. Just make sure your folder with resources is listed via -cp when running java and relative paths in your code corresponds to it.

    Here is an example.

    java -cp ".;first/path/to/resource/folder;second/path;third/path" PackageName.NameOfClassContainingMainMethod

    That said, the resource might be inside of the same folder that your compiled code is in. In that case, there is no need to provide it explicitly via -cp.

    Whenever you are loading a resource in your code by ClassLoader.getResource / getResourceAsStream java looks for it in the classpath. Providing .jar (which is essentially just a zipped folder) and raw folder is just an alternative ways to specify a content to be loaded into classpath.