Core Java

Getting Started with JLine 3

JLine 3 is a powerful Java library for handling console input. It provides features like command-line editing, tab completion, history, and more—similar to what you’d expect in a Bash shell. Let us delve into understanding how JLine 3 enhances the Java command-line experience by offering advanced features like input editing, auto-completion, and cross-platform terminal abstraction.

1. Introduction

Command-line interfaces (CLIs) remain indispensable in a wide array of use cases, ranging from system administration and development tools to DevOps automation pipelines. Their lightweight, scriptable, and keyboard-centric nature makes them ideal for power users and developers alike. In the Java ecosystem, while basic input can be handled using standard classes like Scanner or BufferedReader, these options fall short when it comes to creating user-friendly, interactive CLI applications.

This is where JLine 3 comes into play. JLine is a powerful Java library that brings GNU readline-style functionality into the JVM, enabling developers to build modern, feature-rich command-line experiences. It supports advanced input handling, tab completion, command history, and even custom syntax highlighting, making it an excellent choice for Java developers building CLI tools.

Some of the standout features of JLine 3 include:

  • Terminal abstraction – Supports multiple platforms such as Windows, Unix, and macOS, and integrates smoothly with both console and pseudo-terminal environments.
  • Line editing – Provides user-friendly text editing capabilities, including cursor movement, undo/redo, and clipboard operations, similar to GNU Readline.
  • Command history – Users can navigate previously entered commands using arrow keys, greatly improving productivity.
  • Auto-completion – Offers context-sensitive tab-completion, which can be customized to suit specific commands or DSLs.
  • Syntax highlighting and masking – Useful for secure password inputs and enhanced readability of CLI prompts.

JLine 3 is trusted and integrated into many high-profile Java projects such as:

With its modular architecture and ease of integration, JLine 3 continues to be the go-to solution for Java developers looking to create interactive and ergonomic CLI applications. Whether you’re building an internal tool, a developer utility, or a shell-based interface, JLine 3 empowers you to deliver a professional-grade command-line experience.

2. Java Code Example

2.1 Maven Dependency

To use JLine 3 in your Java application, you need to include the JLine dependency in your pom.xml file. Make sure to use the latest version available on Maven Central.

<dependency>
  <groupId>org.jline</groupId>
  <artifactId>jline</artifactId>
  <version>jar__latest__version</version>
</dependency>

This dependency enables features such as terminal handling, line reading, auto-completion, and command history in Java-based command-line tools.

2.2 Code Example

Below is a full example that demonstrates how to use the JLine library to build a user-friendly Command Line Interface (CLI) application in Java. This example showcases terminal setup, command auto-completion, history management, and graceful exits.

package com.example;

import org.jline.reader.*;
import org.jline.reader.impl.DefaultParser;
import org.jline.reader.impl.LineReaderImpl;
import org.jline.reader.impl.completer.StringsCompleter;
import org.jline.reader.impl.history.DefaultHistory;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;

import java.io.IOException;

/**
 * Full example demonstrating Terminal, LineReader, History, and Completion using JLine 3.
 */
public class JLineFullExample {
    public static void main(String[] args) throws IOException {
        // Step 1: Create a terminal instance using TerminalBuilder
        Terminal terminal = TerminalBuilder.builder()
                .system(true) // Uses the system's terminal (Windows/Linux/Mac)
                .build();

        // Step 2: Define auto-completion options for the CLI
        Completer completer = new StringsCompleter("help", "hello", "version", "exit");

        // Step 3: Set up the LineReader with a parser, completer, and history manager
        LineReader reader = LineReaderBuilder.builder()
                .terminal(terminal)
                .parser(new DefaultParser())  // Parses user input lines
                .completer(completer)         // Adds tab-completion support
                .history(new DefaultHistory()) // Enables command history (arrow up/down)
                .build();

        // Initial welcome message
        terminal.writer().println("Welcome to the JLine Demo CLI!");
        terminal.writer().println("Type 'help' for available commands.\n");

        // Step 4: Start an infinite loop to accept user input
        while (true) {
            String line;
            try {
                // Show prompt and wait for input
                line = reader.readLine("demo> ");
            } catch (UserInterruptException | EndOfFileException e) {
                // Handles Ctrl+C or Ctrl+D to exit
                break;
            }

            if (line == null) continue;
            line = line.trim();

            // Step 5: Command dispatcher - handle recognized commands
            switch (line) {
                case "help":
                    terminal.writer().println("Available commands: help, hello, version, exit");
                    break;
                case "hello":
                    terminal.writer().println("Hello, World!");
                    break;
                case "version":
                    terminal.writer().println("JLine CLI Version 1.0.0");
                    break;
                case "exit":
                    terminal.writer().println("Goodbye!");
                    return;
                default:
                    terminal.writer().println("Unknown command: " + line);
            }

            // Flush output to ensure it's written to terminal
            terminal.flush();
        }
    }
}

This example provides a robust foundation for building interactive CLI tools in Java. Developers can extend this further by integrating complex command parsers, executing system tasks, or incorporating scripting capabilities.

2.2.1 Code Explanation

The given Java code is a complete example of building a command-line interface (CLI) using the JLine 3 library, which offers advanced terminal handling, line editing, history, and auto-completion. It starts by importing required classes from the JLine package and sets up a terminal using TerminalBuilder, configured to use the system terminal. A StringsCompleter is initialized to provide auto-completion for commands like "help", "hello", "version", and "exit". The LineReader is constructed using LineReaderBuilder, integrating the terminal, a DefaultParser for parsing inputs, the defined completer, and a DefaultHistory object for tracking command history. The terminal welcomes the user and enters an infinite loop to continuously prompt the user with "demo> ", using readLine() to read user input. Upon receiving input, it trims whitespace and evaluates the command through a switch statement—responding with appropriate messages for recognized commands and informing the user when an unknown command is entered. Special cases like UserInterruptException (e.g., Ctrl+C) or EndOfFileException (e.g., Ctrl+D) safely break the loop, and if the command is "exit", the application says “Goodbye!” and terminates. The output is written using terminal.writer().println() and flushed to ensure immediate visibility in the terminal.

2.2.2 Code Output

When you run the above Java program, you’ll see an interactive command-line interface. Below is a sample session demonstrating how the user interacts with the CLI. It shows the welcome message, tab completion for commands, and output for various inputs like hello, version, and exit.

Welcome to the JLine Demo CLI!
Type 'help' for available commands.

demo> hel
hello  help

demo> hello
Hello, World!

demo> version
JLine CLI Version 1.0.0

demo> exit
Goodbye!

As shown above, the CLI supports helpful features like tab-completion (e.g., typing hel and pressing TAB suggests hello and help), along with real-time feedback and command history using the up/down arrow keys.

3. Conclusion

JLine 3 is a must-have library if you’re building CLI applications in Java. It makes your application feel more polished by adding features like history, tab completion, and multi-line editing—all without needing to implement them from scratch. Whether you’re creating a developer tool, scripting engine, or a shell-like interface, JLine 3 offers the power and flexibility to deliver a top-tier console experience.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button