Avoid control sequences(like ^[[C) from Java standard inputstream

Viewed 91

Code:

import java.util.Scanner;
public class Try{
  public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a String : ");
    String s = sc.nextLine();
    System.out.println("The Entered String is : " + s);
    System.out.println("The Length of Entered String is : " + s.length());
    sc.close();
  }
}

Output:

┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $java Try
Enter a String : 
hello
The Entered String is : hello
The Length of Entered String is : 5
┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $java Try
Enter a String : 
hello^[[C
The Entered String is : hello
The Length of Entered String is : 8

When I press the arrow keys ^[[C show up instead of the cursor moving (similar thing happens with other arrow keys, escape key, home, end)!

Whats happening here is the second time the string has the characters :

['h', 'e', 'l', 'l', 'o', '\x1b', '[', 'C']

So, the '\x1b', '[', 'C' is the sequence of characters send to the shell from the keyboard for representing right arrow key(cursor forward).

What i want is that these characters will not show up in the shell but the cursor will move (forward, backward, to home, end, etc as per the key pressed).

Processing after taking the input is meaning less as the main aim is to let the cursor be moved!

How can i achieve this in Java?

[EDIT]

The one and only aim is to give the user a exact terminal like experience while using the program.

1 Answers

So I did a lot of searching and googling and as of now I don't think it is possible to do so directly from Java.

But, but we can achieve this and much more with C++ or C.

So, the best and most optimal solution will be to use a C++ library for this.

Now I don't know much of any such preexisting library(for Java) so I wrote my own C++ code and called it from Java using JNI.

And if you think its too complicated to do it every time for such a small issue i have created a very simple Java Library that does all that.

Here is the GitHub Page: https://github.com/Jaysmito101/SeriousConsole

It is very simple to use it.

My code:

import com.jaysmito.sconsole.SeriousConsole;

import java.nio.file.*;
public class Main{
    public static void main(String[] args) throws Exception{
        SeriousConsole.initConsole(Path.of("").toAbsolutePath().toString() + "/libseriousconsole.so");
        SeriousConsole.print("Enter a String : ");
        String s = SeriousConsole.readLine();
        System.out.println("The String entered is: " + s);
    }
}

To compile :

javac -cp SeriousConsole.jar Main.java

To run :

java -cp .:SeriousConsole.jar Main

You can download the jar and so file form the GitHub link.

Note : This library is meant to be a better version of java.io.Console

Related