Question

Hopefully someone can help me with this.

It is my understanding that using a ClassLoader is the most reliable way to load in content.

public class Pipeline{
   public static URL getResource(String filename) {
      return ClassLoader.getSystemResource(filename);
   }

   public static InputStream getResourceAsStream(String filename) {
      return ClassLoader.getSystemResourceAsStream(filename);
   }
}

If you had a file at "[jar bundle]/resources/abc.png" ..You would load it by:

URL url = Pipeline.getResource("resources/abc.png"); 

Loading is simple.
Saving is what's getting me.

I have a program that collects data while running, saves that data on exit, and then loads the data back in next time and keeps adding to it.

Easiest solution I think would be to save back into the jar bundle so that ClassLoader can get at them. Is this even possible? Or recommended?

I don't mind having my resources outside of the jar, just as long as I don't have to resort to 'File' to get at them and save to them. (Unless it can be done cleanly)

folder/application.jar

folder/resources/abc.png

If you could ../ back one from where the ClassLoader is looking it would be easy to cleanly get data from the directory that actually contains the jar file

Pipeline.getResource("../resources/abc.png");

Any ideas?

Was it helpful?

Solution

This isn't really what class loaders are meant for. Loading resources from the class loader is meant so that you can bundle up your application as one package and components can read each other without worrying about how the system you're deploying to is setup.

If the file in the JAR is meant to be changed by the app, then it isn't part of the app and thus probably shouldn't be in the JAR.

I don't have a lot of context on your app, but hopefully my suggestion will be valid for your situation.

I recommend setting a requirement in your app that it has a work area to which it is allowed to read and write and accept a configuration setting that specifies where this directory is. Typical ways to do this in Java are with environment variables, system properties or JNDI settings (for container deployments).

Examples:

  1. Tomcat's startup scripts figure out where it is installed and sets a system property called catalina.home and allows you to over-ride it with an environment variable called CATALINA_HOME.
  2. JBoss looks for JBOSS_HOME
  3. Java application servers typically look for JAVA_HOME to find the JDK.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top