Java: Clear the console

后端 未结 14 2702
青春惊慌失措
青春惊慌失措 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:21

    This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).

    public final static void clearConsole()
    {
        try
        {
            final String os = System.getProperty("os.name");
    
            if (os.contains("Windows"))
            {
                Runtime.getRuntime().exec("cls");
            }
            else
            {
                Runtime.getRuntime().exec("clear");
            }
        }
        catch (final Exception e)
        {
            //  Handle any exceptions.
        }
    }
    

    Note that this method generally will not clear the console if you are running inside an IDE.

提交回复
热议问题