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 the toml4j parser

Adding toml4j dependency

Create an empty maven project and add the 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 a toml example file that is used as a base for parse, reading, and writing the data to it.

## configuration.toml
# this is a 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 containing dotted symbols are allowed for grouping

Read toml file in java

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

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