commands in java to clear the screen

后端 未结 11 819
一向
一向 2020-11-29 07:35

What command in Java will let you clear the console in a command-line application?

相关标签:
11条回答
  • 2020-11-29 08:10

    clearing for bash that is working for me:

    System.out.print(String.format("\033[H\033[2J"));
    
    0 讨论(0)
  • 2020-11-29 08:14

    If none of the above solutions works for you( as in my case ), try this solution:

    new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    

    I'm using Windows 8 and this solution worked for me. Hope it does to you as well. :)

    0 讨论(0)
  • 2020-11-29 08:15

    There is always the obvious (and kludgy)..

    int numRowsInConsole = 60;
    for (int ii=0; ii<numRowsInConsole; ii++) {
        // scroll down one line
        System.out.println("");
    }
    
    0 讨论(0)
  • 2020-11-29 08:15

    To my knowledge Windows 10's Command Window cmd.exe does not natively support ANSI ESC sequences, despite the rumors. To have the:

    final String ANSI_CLS = "\u001b[2J";
    System.out.print(ANSI_CLS);
    

    method work you need a command line emulator that supports ANSI, such as ConEmu64.

    0 讨论(0)
  • 2020-11-29 08:16

    I think what the OP wants is to clear the screen and move the cursor to the home position. For that try:

            final String ANSI_CLS = "\u001b[2J";
            final String ANSI_HOME = "\u001b[H";
            System.out.print(ANSI_CLS + ANSI_HOME);
            System.out.flush();
    
    0 讨论(0)
  • 2020-11-29 08:20

    Run this sample program: it demonstrates how to clear the console using an escape sequence and reposition the cursor to position X=1, Y=1.

    I tested it on several Linux terminals. Don't know, if it works under Windows.
    Perhaps you can tell me ;)

    Read this article about escape sequences.

    import java.io.*;
    
    public class Main {
    
    public static final char ESC = 27;
    
    public static void main(String[] args)
            throws Exception {
        Console c = System.console();
        if (c == null) {
            System.err.println("no console");
            System.exit(1);
        }
    
        // clear screen only the first time
        c.writer().print(ESC + "[2J");
        c.flush();
        Thread.sleep(200);
    
        for (int i = 0; i < 100; ++i) {
            // reposition the cursor to 1|1
            c.writer().print(ESC + "[1;1H");
            c.flush();
    
            c.writer().println("hello " + i);
            c.flush();
    
            Thread.sleep(200);
        }
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题