Use JLine when you want to handle keystrokes on the console character by character in Java

Overview

This entry deals with how to handle input character by character when writing a program that runs console I / O in Java.

background

In Java, there are Streams that handle standard I / O, which allows you to "read" input character by character, but not directly handle keystroke events.

For this reason, for example, when creating a "calculator" program, if you press "+", something will be done immediately, which cannot be achieved with the standard library alone.

Use JLine

What is JLine

JLine3 is a library that you can use when developing CUI applications. It is also used by some well-known OSS.

JLine3 also supports platform-specific terminal control in Windows environments. Since a platform-native library is required here, a method using JNA or JANSI is provided. This entry uses JNA.

Code sample

If you use the code below, you can input each character from the terminal and immediately display it on the standard output.

package com.hrkt.commandlinecalculator;

import lombok.extern.slf4j.Slf4j;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class CommandlineInterface {
    public void run(String... args) {
        log.info("hello");

        try(Terminal terminal = TerminalBuilder.terminal()) {
            int ch = 0;
            while ((ch = terminal.reader().read()) != 0x09){
                // TAB(0x09)Exit with
                char c = (char)ch;
                System.out.println(String.format("%d, %c", ch, ch));
            }
        } catch(IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}

The movement is as shown in the figure below.

char-by-char.png

in conclusion

In this entry, I showed you how to handle keystrokes from the console in Java. I see articles that use JLine2, but it has been developed and it is recommended to use JLine3.

Code sample

A working sample can be found below.

https://github.com/hrkt/commandline-calculator/releases/tag/0.0.2

Recommended Posts

Use JLine when you want to handle keystrokes on the console character by character in Java
When you want to use the method outside
The first thing to do when you want to be happy with Heroku on GitHub with Eclipse in Java
When you want to dynamically replace Annotation in Java8
# 1_JAVA I want to get the index number by specifying one character in the character string.
Code to use when you want to process Json with only standard library in Java
When you want to reflect the Master Branch information in the Current Branch you are currently working on
I want to get the IP address when connecting to Wi-Fi in Java
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
When you want to bind InputStream in JDBI3
A note when you want Tuple in Java
[Swift] Use nonzeroBitCount when you want popcnt in Swift
I want you to use Scala as Better Java for the time being
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
If you want to recreate the instance in cloud9
Notes on how to use regular expressions in Java
[Android Studio] I want to set restrictions on the values registered in EditText [Java]
Summary of how to use the proxy set in IE when connecting with Java
[java tool] A useful tool when you want to send the ipmsg log of PC-A to the specified PC on a regular basis.
[Ruby] When you want to assign the result obtained by conditional branching to a variable and put it in the argument
I want to use screen sharing on the login screen on Ubuntu 18
I want to use Java Applet easily on the command line without using an IDE
Things you often use when doing web development in Java
I want to use the Java 8 DateTime API slowly (now)
When you want to implement Java library testing in Spock with multi-module in Gradle in Android Studio 3
How to switch Java in the OpenJDK era on Mac
When you want to change the MySQL password of docker-compose
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
Delegate is convenient to use when you want to reuse parts
I want to simplify the conditional if-else statement in Java
Input to the Java console
[Swift] When you want to know if the number of characters in a String matches a certain number ...
I want to judge the necessity of testing by comparing the difference of class files when refactoring Java
Comparison of version strings (Java implementation) when you want to branch the process between two versions
A memorandum when you want to see the data acquired by Jena & SPARQL for each variable.
How to write when you want to handle "array of C language strings" like argv [] in Ruby-FFI
What to do when you want to know the source position where the method is defined in binding.pry
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
When the character string passed to C ++ by JNA is garbled
ProxyFactory is convenient when you want to test AOP in Spring!
When you want to ZIP download the image data saved locally
If you want to change the Java development environment from Eclipse
[Java] I want to perform distinct with the key in the object
How to solve the unknown error when using slf4j in Java
I tried to display the calendar on the Eclipse console using Java.
Practice to use when you want to execute different processing groups serially
Guess the character code in Java
How to use classes in Java?
Do you use Stream in Java?
Resolved the error that occurred when trying to use Spark in an environment where Java 8 and Java 11 coexist.
[Rails + Webpacker] I want to use images of assets! Until you can view the image in Vue.js
[Ruby] I want to output only the odd-numbered characters in the character string
A memo when you want to clear the time part of the calendar
[Java] Display the bit string stored in the byte type variable on the console
Summary of means when you want to communicate with HTTP on Android
What wasn't fair use in the diversion of Java APIs on Android
How to find the total number of pages when paging in Java
I want to display an error message when registering in the database
How to debug the processing in the Ruby on Rails model only on the console
To you who were told "Don't use Stream API" in the field
[Java Spring MVC] I want to use DI in my own class