Ini File - Read and Write java

This tutorial covers the How to parse/read or write of ini file with examples ..

Read/ write ini data files in java using ini4j parser

Java language provides various third party libraries to read and write ini files - ini4j parser This post talks about ini4j parser

Adding ini4j dependency

Create a empty maven project and add 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 ini example file which is used as a base for parse,read and write the data to it.

;config.toml
; 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 parse ini file in java using ini4j library. It reads ini file using TOML.java datasources.

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);
	}
}