I've developed a simple app using Sparkjava. I'm using Intellij, and when I run my tests, or run the app locally, all my resources are files.
However, when I deploy, the whole thing runs as a jar file. As such, I need a way to read my resources off the filesystem or the jar, depending on how the app is launched. The following code gets the job done, but it looks clumsy:
String startedOffFile = new java.io.File(Main.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getName();
InputStream inputStream;
if(startedOffFile.endsWith(".jar")) {
ClassLoader cl = PropertiesParser.class.getClassLoader();
inputStream = cl.getResourceAsStream("myapp.dev.properties");
} else {
inputStream = new FileInputStream(filename);
}
Is there a cleaner/simpler way?
If you're using Maven with IntelliJ, just put the configuration properties file inside the src/main/resources
directory in the module. If you're not using Maven then put the properties file in the root of your source tree (outside any package - like: src/myapp.dev.properties
).
After packaging/exporting of the JAR the file will be accessible with new Object().getClass().getClassLoader().getResourceAsStream("myapp.dev.properties")
(the new Object()...
is used, because in some cases/platforms the static ClassLoader is not defined).
The same classpath is used by the IntelliJ/Eclipse environment, which means there is no need for a special case for loading the files.
If you need to differentiate between development and production properties. You can use Maven profiles for build time packaging or you can load the properties with a variable using the -D switch.