java-course

TOML

..

TOML (Tom’s Obvious, Minimal Language) is a configuration file format designed for clarity and obviousness. It aims to be easily readable and writable by humans and simply parsed and generated by machines. TOML is particularly suitable for configuration files and has become popular due to its simplicity and clarity.

TOML Structure

TOML is organized into tables, which are collections of key-value pairs. The main elements of TOML’s structure include:

  1. Key-Value Pairs: These are the basic data elements.
  2. Tables: Groups of keys that form logically related data, presented as tables.
  3. Arrays (lists): Lists of values or tables, supporting homogeneous collections.
  4. Date and Time: TOML supports native data types for dates and times.

Example of a TOML File

# Example TOML configuration file
title = "Example TOML"

[owner]
name = "John Doe"
dob = 1979-05-27T07:32:00Z

[database]
server = "192.168.1.1"
ports = [8001, 8001, 8002]
connection_max = 5000
enabled = true

[servers]

  # Indentation helps with visual grouping
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

Working with TOML in Java

Several libraries are available for working with TOML in Java. One of the popular libraries for TOML manipulation in Java is toml4j.

Adding toml4j to Your Project

If you are using Maven, add the following dependency to your pom.xml:

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

Example of Using toml4j

Here’s how you can parse and generate TOML data in Java using toml4j:

import com.moandjiezana.toml.Toml;

import java.util.Map;
import java.io.File;

public class Main {
    public static void main(String[] args) {
        // Loading and parsing a TOML file
        Toml toml = new Toml().read(new File("config.toml"));
        String title = toml.getString("title");
        Map<String, Object> owner = toml.getTable("owner").toMap();

        System.out.println("Title: " + title);
        System.out.println("Owner: " + owner);

        // Example of creating a TOML string
        Toml tomlToWrite = new Toml().read("[new]\ndata = 'example'");
        System.out.println(tomlToWrite);
    }
}

Advantages of TOML

TOML offers a simple and intuitive approach to managing configuration files, particularly in environments where data transparency and accessibility are important.