Getting Started with JLine 3: Building Interactive Java CLI Applications
This article introduces JLine 3, a Java library that adds GNU‑readline‑style features such as line editing, history, auto‑completion, and syntax highlighting to command‑line tools, and provides Maven setup, a complete code example, detailed explanation, and sample output for building robust interactive CLI applications.
Command‑line interfaces (CLIs) remain essential in many scenarios, and JLine 3 provides a powerful Java library that brings GNU readline‑like capabilities to the JVM, enabling developers to create modern, feature‑rich interactive CLI applications.
Key features of JLine 3 include:
Terminal abstraction supporting Windows, Unix, macOS and pseudo‑terminal environments.
Line editing with cursor movement, undo/redo, and clipboard operations similar to GNU Readline.
Command history navigation using arrow keys.
Context‑aware auto‑completion that can be customized for specific commands or DSLs.
Syntax highlighting and masking for secure password input.
JLine 3 is used by many well‑known Java projects such as Apache Karaf, Apache Cassandra (cqlsh), and Groovy Shell (groovysh), making it a trusted choice for building interactive shells.
2. Java Code Example
2.1 Maven Dependency
To use JLine 3 in a Java project, add the following dependency to your pom.xml (replace jar__latest__version with the current version):
<dependency>
<groupId>org.jline</groupId>
<artifactId>jline</artifactId>
<version>jar__latest__version</version>
</dependency>2.2 Full Code Example
The following Java program demonstrates a complete interactive CLI built with JLine 3, covering terminal setup, auto‑completion, history management, and graceful shutdown:
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;
/**
* Demonstrates terminal, LineReader, history and completer features using JLine 3.
*/
public class JLineFullExample {
public static void main(String[] args) throws IOException {
// Step 1: Create a terminal instance
Terminal terminal = TerminalBuilder.builder()
.system(true) // use system terminal (Windows/Linux/Mac)
.build();
// Step 2: Define auto‑completion options
Completer completer = new StringsCompleter("help", "hello", "version", "exit");
// Step 3: Set up LineReader with parser, completer and history
LineReader reader = LineReaderBuilder.builder()
.terminal(terminal)
.parser(new DefaultParser()) // parse user input lines
.completer(completer) // enable tab completion
.history(new DefaultHistory()) // enable command history (arrow keys)
.build();
// Welcome message
terminal.writer().println("欢迎来到 JLine 演示 CLI!");
terminal.writer().println("输入 'help' 查看可用命令.\n");
// Step 4: Main loop to read user input
while (true) {
String line;
try {
// Show prompt and wait for input
line = reader.readLine("demo> ");
} catch (UserInterruptException | EndOfFileException e) {
// Handle Ctrl+C or Ctrl+D to exit
break;
}
if (line == null) continue;
line = line.trim();
// Step 5: Command dispatcher
switch (line) {
case "help":
terminal.writer().println("可用命令:help、hello、version、exit");
break;
case "hello":
terminal.writer().println("Hello, World!");
break;
case "version":
terminal.writer().println("JLine CLI 版本 1.0.0");
break;
case "exit":
terminal.writer().println("Goodbye!");
return;
default:
terminal.writer().println("未知命令:" + line);
}
// Flush output to ensure it appears immediately
terminal.flush();
}
}
}The program initializes a Terminal via TerminalBuilder , sets up a StringsCompleter for commands, builds a LineReader with a DefaultParser and DefaultHistory , then enters an infinite loop that reads input, trims it, and dispatches commands using a switch statement. It gracefully handles UserInterruptException (Ctrl+C) and EndOfFileException (Ctrl+D), and exits when the user types exit .
2.2.2 Sample Output
Running the program produces an interactive session similar to the following:
欢迎来到 JLine 演示 CLI!
输入 'help' 查看可用命令。
demo> hel
hello help
demo> hello
Hello, World!
demo> version
JLine CLI 版本 1.0.0
demo> exit
Goodbye!The CLI supports features such as tab‑completion (e.g., typing hel and pressing TAB suggests hello and help ) and real‑time command history navigation using the up/down arrow keys.
Conclusion
If you are building CLI applications in Java, JLine 3 is an essential library. It adds history, auto‑completion, multi‑line editing, and other ergonomic features without requiring you to implement them from scratch, making it ideal for developer tools, script engines, or shell‑like interfaces.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.