Search code examples
javaini4j

INI4J - Delete Section


How can I remove a section with or without the Java library INI4J?

This does not work

Wini ini = new Wini(File);
System.out.println(Integer.toString(Position));
ini.remove(Integer.toString(Position));

I also tried it with the ConfigParser.


Solution

  • Your code doesn't do anything and definitely does not compile. Wini is not the correct class, per the ini4j docs you need to instantiate an Ini object and remove/create sections using the Section object.

    I would highly recommend reading through the Ini4J documentation. The tutorials are great and the examples provided answer your very question!

    Though you can also keep reading too...

    Given the Ini File

    [Section]

    somekey = somevalue

    somekey2 = somevalue2

    somekey3 = somevalue3

    (Using Ini4J)

    We can write

    Ini iniFile = new Ini(new FileInputStream(new File("/path/to/the/ini/file.ini")));
    /*
     * Removes a key/value you pair from a section
     */
    // Check to ensure the section exists
    if (iniFile.containsKey("Section")) { 
        // Get the section, a section contains a Map<String,String> of all associated settings
        Section s = iniFile.get("Section");
    
        // Check for a given key<->value mapping
        if ( s.containsKey("somekey") ) { 
            // remove said key<->value mapping
            s.remove("somekey");
        }
    }
    
    /*
     * Removes an entire section
     */
    if (iniFile.containsKey("Section")) { 
        // Gets the section and removes it from the file
        iniFile.remove(iniFile.get("Section"));
    }
    
    // Store our changes back out into the file
    iniFile.store(new FileOutputStream(new File("/path/to/the/ini/file.ini")));