0

I want to read the configuration file outside the jar, how should I do?
I tried classloader.getResourceAsStream("config.xml") and succeeded while I am running the code inside Intellij. Now I want to build the jars to a folder and place the config.xml under the same folder, not inside the jar, but the program fails to detect the config.xml.

Is there a graceful way of reading the config.xml instead of using File with relative path in the code, which doesn't work while debugging/running inside the IDE?

Hawii Hawii
  • 47
  • 1
  • 5
  • Your code looks for a resource named config.xml in the classpath. So, if the folder containing this file is in the runtime classpath, that will work. Otherwise, it won't. As simple as that. – JB Nizet Aug 13 '19 at 16:40
  • Instead of relying on the classpath, try reading it as a normal file. – Mark Rotteveel Aug 13 '19 at 18:07

1 Answers1

1

Yes, turn it into a system property, and provide it to anything running any Java process/application.

Let's say you have a config.xml file located inside /some/path/down/the/line/, then you can do: java --classpath ... -Dapp.config=/some/path/down/the/line/config.xml tld.domain.Application.

Then all you have to do in your Java code is to reference that name/path: final String configFile = System.getProperty("app.config");, and use any well-known routine to read it from there.

Basically, you have to make sure the file/path/location is provided somehow to the Java classpath.

x80486
  • 6,627
  • 5
  • 52
  • 111