commands in java to clear the screen

后端 未结 11 820
一向
一向 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:21

    There are two very simple ways to solve this, the first is the brute force option:

    for (int i=1; i<=10; i++)
        System.out.println("\n");
    

    The problem with this however is that it only pseudo clears the screen, you can scroll up to see the data, but don't fear, there is another way!

    System.out.println("\f");
    

    Voila! That should do the trick, although your cursor will be situated on the second line of the console after the screen is cleared.

    0 讨论(0)
  • 2020-11-29 08:22
    System.out.println("Hello!");
    

    prints the specified string and then moves the cursor to the next line.

    System.out.print("Hello!");
    

    prints the specified string and leaves the cursor immediately after that string.

    To solve the problem, identified above, of the cursor being on the second line of the console, use print instead of println.

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

    Clearing a screen generally requires sending special control sequences specific to the screen/terminal that your application is running under. Options:

    1. If you know you will always running under a specific terminal and can find the proper control sequences to clear the screen for that terminal, just output those sequences. If you tell us the screen, we may be able to tell you the sequence (its likely somewhat ANSI/VT100/VT220 -compatible).

    2. Externally ensure your app is always run in a desired terminal, e.g. a script to start your app starts the app in the desired terminal. Then output the necessary character sequence to clear the screen.

    3. Take control of the terminal by using a terminal emulation library, i.e. you app is now a windowing app that creates a terminal window screen for the user to use. You then control what terminal you are emulating and will know what control sequences are needed.

    4. Use a terminal library (e.g. like the historic curses library) that detects the terminal and provides an uniform interface to its features. See this question:

      What's a good Java, curses-like, library for terminal applications?

    5. Fake it by writing a bunch of lines to the screen.

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

    It depends on your console but if it supports ANSI escape sequences, then try this..

    final static String ESC = "\033[";
    System.out.print(ESC + "2J"); 
    
    0 讨论(0)
  • 2020-11-29 08:31

    I did this in BlueJ and it worked perfectly: Try System.out.print("\f");

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