Java: Clear the console

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

    You need to use JNI.

    First of all use create a .dll using visual studio, that call system("cls"). After that use JNI to use this DDL.

    I found this article that is nice:

    http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 00:22

    You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.

    Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it

    After these configurations, you can manage your console with control characters like:

    \t - tab.

    \b - backspace (a step backward in the text or deletion of a single character).

    \n - new line.

    \r - carriage return. ()

    \f - form feed.

    More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php

    0 讨论(0)
  • 2020-11-22 00:24

    Try this: only works on console, not in NetBeans integrated console.

        public static void cls(){
    try {
    
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
    

    }

    0 讨论(0)
  • 2020-11-22 00:26

    A way to get this can be print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.

    Here is a sample code:

    for (int i = 0; i < 50; ++i) System.out.println();
    
    0 讨论(0)
  • 2020-11-22 00:29

    Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -

    for(int clear = 0; clear < 1000; clear++)
      {
         System.out.println("\b") ;
      }
    

    Hope this is useful

    0 讨论(0)
提交回复
热议问题