JLine In Java

JLine is an open-source framework for handling console interactions in Java applications.

说明

JLine 是一个用于 Java 应用程序中处理控制台交互的开源框架。它提供了一些功能来实现交互式的命令行界面,例如支持命令历史记录、自动补全、颜色输出等。

使用 JLine,你可以方便地创建一个交互式的命令行界面,用户可以通过控制台输入命令并得到相应的输出。它提供了一些基本方法来读取用户输入,并支持编辑功能(例如使用方向键移动光标、删除字符等)和自动补全功能(根据已输入的内容提供候选选项)。

JLine 还可以帮助你处理复杂的控制台输出,例如在命令行中使用不同的颜色和样式输出文本。它提供了一些 API 来控制文本的颜色、背景色和样式,使你可以更好地呈现信息。

示例

import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Example
 * This Java class demonstrates how to execute commands and handle the output in a command-line interface.
 *
 * Usage
 * Compile the Java class.
 * Run the compiled class.
 * $ javac Example.java
 * $ java Example
 * Enter commands in the command-line interface (CLI).
 * Description
 * The Example class provides a CLI interface where you can enter commands to be executed. The Terminal and LineReader classes from the JLine library are used to create the CLI interface.
 *
 * The main method sets up the CLI environment and enters a loop to read user input. Each line of input is passed to the exec method, which executes the command using ProcessBuilder.
 *
 * The exec method starts a new process to execute the command and redirects the standard error to the standard output. It then creates two separate threads to handle the standard output and standard error streams respectively. These threads read the output line by line and print it to the console. After that, it waits for the command to complete and prints the exit code. Finally, it waits for the output and error threads to finish.
 *
 * Examples
 *
 * > echo Hello, world!
 * > input: Hello, world!
 * > 命令执行结束,退出码: 0
 * > ls
 * > input: file1.txt
 * > input: file2.txt
 * > 命令执行结束,退出码: 0
 * > invalid-command
 * > error: 'invalid-command' is not recognized as an internal or external command,
 * > operable program or batch file.
 * > 命令执行结束,退出码: 1
 * > exit
 * > In the example above, the user enters various commands and the output is displayed accordingly. The exit code indicates whether the command executed successfully or not.
 *
 * Feel free to modify and expand upon this example to suit your needs.
 *
 * Dependencies
 * JLine library is used for the CLI interface. Make sure to include the JLine library in your project.
 */
public class Example {

    public static void main(String[] args) throws IOException {
        Terminal terminal = TerminalBuilder.builder().build();
        LineReader lineReader = LineReaderBuilder.builder().terminal(terminal).build();
        String line;
        while ((line = lineReader.readLine("> ")) != null) {
            // 在此处处理命令行输入的line
            exec(line);
        }
    }

    /**
     * 执行命令
     */
    static void exec(String cmd) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", cmd);
            processBuilder.redirectErrorStream(true); // 将错误输出合并到标准输出

            Process process = processBuilder.start();

            // 处理标准输出
            Thread outputThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("input: " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            // 处理标准错误
            Thread errorThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.err.println("error: " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            // 启动线程处理输出和错误
            outputThread.start();
            errorThread.start();

            // 等待命令执行完成
            int exitCode = process.waitFor();
            System.out.println("命令执行结束,退出码: " + exitCode);

            // 等待线程执行完成
            outputThread.join();
            errorThread.join();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

P("Struggler") ?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值