Read/ write ini data files in Java using the ini4j parser

Java language provides various third-party libraries to read and write ini files

  • ini4j parser This post talks about the ini4j parser

Adding ini4j dependency

Create an empty maven project and add the ini4j maven dependency

For maven projects, add the following dependency

<dependency>
    <groupId>org.ini4j</groupId>
    <artifactId>ini4j</artifactId>
    <version>0.5.4</version>
</dependency>

for Gradle-based projects, please add the following dependency

compile "org.ini4j:ini4j:0.5.4"

Sample INI data example file

Following is the ini example file which is used as a base for parse, reading, and writing the data to it.

;config.ini
; Created by Franc
[Author]
name=Franc
updateDate=20-03-2020.

[database]
server=192.168.10
port=43
username="root"

Read INI file in Java

The below example parses the ini file in Java using the ini4j library. It reads ini files using TOML.java data sources.

package org.w3schools.io.ini;
import java.io.InputStream;
import org.ini4j.Wini;

public class ReadIni2AsObject {
    private static final String SAMPLE_INI_FILE = "config.ini";
    public static void main(String[] args) throws Exception {
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classloader.getResourceAsStream(SAMPLE_INI_FILE);
        Wini ini = new Wini(inputStream);
        String name = ini.get("Author", "name", String.class);
        String updateDate = ini.get("Author", "updateDate", String.class);
        System.out.println("name=" + name);
        System.out.println("updateDate=" + updateDate);
        String server = ini.get("database", "server", String.class);
        Integer port = ini.get("database", "port", Integer.class);
        String username = ini.get("database", "username", String.class);

        System.out.println("server= " + server);
        System.out.println("port = " + port);
        System.out.println("username = " + username);
    }
}