Java: Clear the console

后端 未结 14 2703
青春惊慌失措
青春惊慌失措 2020-11-21 23:26

Can any body please tell me what code is used for clear screen in Java? For example in C++

system(\"CLS\");

What code is used in Java for

14条回答
  •  面向向阳花
    2020-11-22 00:09

    If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.

    Something like the following code worked for me:

    import jline.console.ConsoleReader;
    
    public class JLineTest
    {
        public static void main(String... args)
        throws Exception
        {
            ConsoleReader r = new ConsoleReader();
    
            while (true)
            {
                r.println("Good morning");
                r.flush();
    
                String input = r.readLine("prompt>");
    
                if ("clear".equals(input))
                    r.clearScreen();
                else if ("exit".equals(input))
                    return;
                else
                    System.out.println("You typed '" + input + "'.");
    
            }
        }
    }
    

    When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.

提交回复
热议问题