TOML - java example

This tutorial covers toml example file ..

Read/ write toml data files in java language using toml4j parser

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

  • toml4j parser
  • tomlj library This post talks about toml4j parser

Adding toml4j dependency

Create a empty maven project and add toml4j maven dependency

For maven projects, add the following dependency

<dependency>
  <groupId>com.moandjiezana.toml</groupId>
  <artifactId>toml4j</artifactId>
  <version>0.7.2</version>
</dependency>

for gradle based projects, please add the following dependency

compile "com.moandjiezana.toml:toml4j:0.7.2"

Sample TOML data example file

Following is toml example file which is used as a base for parse,read and write the data to it.

## configuration.toml
# this is sample file
key="value"
test_key="value"
956="value"
key-1="value"
 key = "value" #keys with spaces are allowed
"key" = "value" # quoted keys are valid
dev.db.url="localhost" # keys contains dotted symbol are allowed for grouping

Read toml file in java

The below example parse toml file in java using toml4j library. It reads TOML file using TOML.java datasources

package org.w3schools.io.toml;

import java.io.InputStream;

import com.moandjiezana.toml.Toml;

/**
 * TOML Parser for reading java
 *
 */
public class App {
	private static final String SAMPLE_TOML_FILE= "config.toml";

	public static void main(String[] args) throws Exception {
		App main = new App();
        InputStream stream= main.getClass().getClassLoader().getResourceAsStream(SAMPLE_TOML_FILE);

		Toml toml = new Toml().read(stream);
		String title = toml.getString("title");
		System.out.println("title = " + title);
		String dbHostname= toml.getString("database.hostname");
		Long dbPort= toml.getLong("database.port");
		String dbUsername= toml.getString("database.username");
		String dbPassword= toml.getString("database.password");
		Boolean dbSsl= toml.getBoolean("database.isSSL");

		System.out.println("hostname = " + dbHostname);
		System.out.println("port = " +dbPort);
		System.out.println("username = " + dbUsername);
		System.out.println("password = " + dbPassword);
		System.out.println("isSSL = " + dbSsl);

	}
}

Output is

title = erp application
hostname = localhost
port = 8001
username = root
password = asdfasdfads
isSSL = true

com.moandjiezana.toml.Toml.Toml is the main class ()read

Toml has reloaded methods ()

Toml.read(IntpuStream) Toml.read(FIle)

Read and parse toml file content into java

Prev