'Java: Moving the Console cursor up a line

First let me clear out i am new to programming and hope that i am using the right terminology.

I using the System.out.print(""); Method to print to the Windows Console: System.out.print("Backspace b"); //Output: Backspace b
So the cursor is now "behind" the b, if i type in System.out.print("\b"); the curser moves one to the left, deleting the "b". -->
System.out.print("Backspace b"); //Output: Backspace b System.out.print("\bh"); //Output: Backspace h

Now if i Type in System.out.print("\n\bh"); the output isn't Backspace bh but:
"Backspace b h"

How can i manage that the cursor goes back one line "up" and to it's far right. Something line a "minus \n" or "not \n", so that it reads Backspace bh?
Is there something like that in Java?



Solution 1:[1]

It's impossible without third party libraries. I've done extensive research on this as I've been working on console games for the past week and from what I can tell you can either require JNI, JNA, Jansi, or JLine which will require Jansi or JNA. Personally I recommend JLine as all the others will require you to write C or C++.

If you say want to go up so many lines you could do something like this with JLine.

import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.InfoCmp;
import java.io.IOException;

public class CursorStuff
{
    static Terminal terminal;

    public static void main(String[] args) throws IOException
    {
        terminal = TerminalBuilder.terminal();
        System.out.println("1");
        System.out.println("2");
        System.out.println("3");
        System.out.println("This line will get overwritten by the terminal path");
        goBackLines(3);
        System.out.println("back 3 overwriting 2");
    }

    public static void goBackLines(int remove)
    {
        for(int i = 0; i < remove; i++)
        {
            terminal.puts(InfoCmp.Capability.cursor_up);
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SpyderCoder