Search code examples
javabufferedreaderfilereaderiniini4j

Reading .ini File When Converted into Runnable Jar File


I have a project which I am going to convert it into runnable jar file. I am storing some of the configurations in my ini file with using ini4j.

It works when I simply set the directory getConf = new Ini(new FileReader(path));, but it wont work when I use getResourceAsStream()

public class IniReader {

// When I set it like that, it works..
private static String path = "../conf.ini";

public static String readIni(String val, String getOb, String fetchOb) {
    Ini getConf = null;

    try {
    // When I set it like that, it works..
        getConf = new Ini(new FileReader(path));

        // I want to use this version but I am getting null error.
        //getConf = new Ini(new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.ini"))));

    } catch (InvalidFileFormatException e) {
        System.err.print("Error InvalidFileFormat : " + e.getMessage() + "\n");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.err.print("Error FileNotFoundException : " + e.getMessage() + "\n");
        e.printStackTrace();
    } catch (IOException e) {
        System.err.print("Error IOException : " + e.getMessage() + "\n");
        e.printStackTrace();
    }
    return val = getConf.get(getOb).fetch(fetchOb);
}

When I try to read my iniFile I am getting the error below;

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:113)
    at org.ini4j.Ini.load(Ini.java:104)
    at org.ini4j.Ini.<init>(Ini.java:56)
    at com.test.ttf.IniReader.readIni(IniReader.java:28)
    at com.test.ttf.SlashSCR.InitProg(SlashSCR.java:116)
    at com.test.ttf.InitProg.main(InitProg.java:18)

This is where I want to read .ini file

enter image description here

EDIT

I also tried the following;

    Ini getConf= new Ini();
    getConf.load(Thread.currentThread().getContextClassLoader().getClass().getResourceAsStream("../conf.ini"));

Solution

  • When you want to load the config from the jar, you can use the path getResource() and getResourceAsStream() functions. The NullPointerException indicates (most likely, because it is always hard to tell with many statements on one line) that the resource was not found (which silently returns null)

    If you want to load it from a local file, then you just do it the original method (with the FileReader) . However you have to set the path relative to the execution directory (where you run java from). This most likely is the same directory as your jar. In that case you should use "conf.ini" instead of "../conf.ini"