0
import java.util.*;
import java.io.*;

class TreeSetPro
{
    public static void main(String $[] )throws IOException
    {
        TreeSet<String> alpha=new TreeSet<String>();

        alpha.add("apple");
        alpha.add("Apple");
        alpha.add("Ab");
        alpha.add("applet");

        System.out.println(alpha);

        String osname = System.getProperty("os.name");

        if (osname.contains("Windows"))
        {
            Runtime.getRuntime().exec("cls"); //java.io.IOException: Cannot 
            run program "cls"
        }
        else
        {
            Runtime.getRuntime().exec("clear"); //java.io.IOException: 
            Cannot run program "clear"
        }
    }
}

I went through nearly all of the post related to clearing the console in java but none of them worked for me. I am using windows 8.1.

How am I supposed to clear the console??

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Udesh
  • 2,415
  • 2
  • 22
  • 32
  • 3
    Having said that: the console isn't meant to be cleared from a Java perspective. It is a line by line "output" device and one should simply accept its limitations. If you really need or want a "better" user experience rather consider to create a gui application. – GhostCat Mar 12 '19 at 04:37
  • @GhostCat the link which you have shared I have gone through that. – Udesh Mar 12 '19 at 04:38
  • like system("cls"); – Udesh Mar 12 '19 at 04:39
  • works well in c++ – Udesh Mar 12 '19 at 04:39

2 Answers2

1

Having tried multiple IDE's, the console isn't meant to be 'cleared' according to Java, whereas in C# or C++ yes you can clear the console because of the way that C# applications are implemented (see all the cmd stuff we sometimes go thru). And since Java is a high-level language, there is really no need for clearing the console from logs, etc...

Isaí Hinojos
  • 172
  • 2
  • 11
  • can't I make an exe in c++ just to clear the console & run that exe file through java. – Udesh Mar 12 '19 at 04:46
  • 1
    You´d have to first run your java application in the cmd, then invoke the inheritIO() so when your java application detects a console (not an IDE debugger console), then you can clear it. – Isaí Hinojos Mar 12 '19 at 04:55
1

It is a line by line output, thus for administrative purpose it cannot be cleared. An alternative method to this is printing out bunch of blank spaces which gives an impression that it is cleared. Even commands like cls/clear puts enough blank spaces.