ini4j Is not finding existing key in .ini file

1.1k views Asked by At

So i have this block of code that is supposed to check and make sure the required keys exist but nomatter if they exist or not it will always call the code in the if block

else {
    Wini ini = new Wini(new File("config.ini"));
    if(!ini.containsKey("nick") || !ini.containsKey("serverHostname") || !ini.containsKey("serverPort") || !ini.containsKey("defaultChannel") || !ini.containsKey("adminNick") || !ini.containsKey("adminHostname")) {
        System.out.println("One or more keys in your configuration do not exist, Remaking configuration");
        ini.clear();
        ini.add("Config");
        System.out.print("Nickname: ");
        ini.put("Config", "nick", input.next());
        System.out.print("Server Hostname: ");
        ini.put("Config", "serverHostname", input.next());
        System.out.print("Server Port: ");
        ini.put("Config", "serverPort", input.nextInt());
        System.out.print("Default Channel: ");
        ini.put("Config", "defaultChannel", input.next());
        ini.add("Administration");
        System.out.print("Bot Administrator Nickname: ");
        ini.put("Administration", "adminNick", input.next());
        System.out.print("Bot Administrator Hostname: ");
        ini.put("Administration", "adminHostname", input.next());
        ini.store();
        System.out.println("Configuration file Remade, Continuing with startup");
    }

EDIT: This is the config.ini:

[Config]
nick = Craftxbot
serverHostname = irc.alphachat.net
serverPort = 6667
defaultChannel = #minecraftchat
adminNick = craftxbox
adminHostname = craftxbox.tk
3

There are 3 answers

1
Peng On BEST ANSWER

Instead of calling containsKey() on the specific section, here you are calling ini.containsKey(sec) on the ini object (the entire ini file), meaning that you are checking the existence of Section sec in the document.

You should call sec.containsKey(key) on the specific Section to check the existence of key under sec. So you code should look like

 Wini ini = new Wini(new File("config.ini"));
 Ini.Section sec = ini.get("Config");  
    if(!sec.containsKey("nick") || !sec.containsKey("serverHostname") || !sec.containsKey("serverPort") || !sec.containsKey("defaultChannel") || !sec.containsKey("adminNick") || !sec.containsKey("adminHostname")) {

    }
1
J Fabian Meier On

I do not see the empty key in your config file.

Therefore,

 !ini.containsKey("")

will always evaluate to true.

1
Stephen C On

It difficult to be sure about this1, but I suspect that containsKey should not be used like that. Since you have a ini file with sections, I think you should be using containsKey in the "Config" section.

There are some examples here: http://www.massapi.com/method/org/ini4j/Profile/Section.containsKey.html


1 ... given the obvious shortcomings of the javadocs for ini4j.