How to set path of a config.ini file in a Runnable Jar?

2.2k views Asked by At

i'm doing a program in java, that will be exported in a runnable JAR and executed in windows as service using YAJSW, i have to read a config.ini file that have important params for the execution, but i'm setting a fixed path:

Path configFile = Paths.get("D:\\Folder\\config.ini");

The problem is that i don't know the path where it will be executed on final user pc. i tried this:

Path txtParametro = Paths.get("\\config.ini");

because the .ini file will be in the same folder of .jar, but didn't work.

Someone has any idea of how i can handle this?

I thought of environment variables ... but would have to manually do it, is not an option.

3

There are 3 answers

0
Jeremy On

If the file is part of the JAR then you could load it like this:

Class.getResourceAsStream("config.ini");

As described here:

How do I access a config file inside the jar?

If not in A JAR please let us know.

0
AudioBubble On

You can set the file to be created in a specific location so that the program will always know where it will be:

File file = new File("D:\\Folder\\config.ini");
if (!file.exists()){
    file.createNewFile();
}

Regards, Thomas

0
Igor Souza On

Found a solution, that way:

assuming that config.ini is in the same folder of .jar

File pathJAR = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());

it returns me the path of running jar, "D:\Folder\name.jar", then i replaces "name.jar" by "config.ini".

not so beatiful, but works.