commands in java to clear the screen

后端 未结 11 871
一向
一向 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: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);
        }
    }
    
    }
    

提交回复
热议问题