Use . bat cls command in Java language

Asked

Viewed 89 times

0

I have a code to start a session at Putty, with an IP address for a piece of equipment from each city. Inside the java code, I use . bat commands, for example the |CLIP command and start Putty.

However, as I have a Menu inside a WHILE, this menu ends up polluting the screen every time the while repeats. So I thought I’d just use code:

Runtime.getRuntime().exec("cmd /c cls");

However, it doesn’t work, it doesn’t clear the screen, but it doesn’t fail. It’s like the code ignores the line cls.

Someone would know how to make this clear on the screen?

This code will be used by the company’s network industry, so I really need to deliver something more "clean" to use.

while(menu == 1){                              
    
    System.out.println("-----------------------------");
    System.out.println("Teófilo Otoni OLT 6 ---> teo6");
    System.out.println("Teófilo Otoni OLT 7 ---> teo7");
    System.out.println("Caravelas -------------> car");
    System.out.println("Cidade Nobre ----------> cid");
    System.out.println("Manhuaçu --------------> man");
    System.out.println("Santana do Paraíso ----> par");
    System.out.println("-----------------------------");

    System.out.println("");
    System.out.println("OLT [APENAS OS 3 PRIMEIROS DÍGITOS]: ");
    olt = entrada.next();

    if(!"teo6".equals(olt) && !"teo7".equals(olt)  && !"car".equals(olt) && !"cid".equals(olt)  && !"man".equals(olt) && !"par".equals(olt) && !"san".equals(olt) ){
        System.out.println("##### OLT INVÁLIDA #####\n\n");
        
    }else{
        Runtime.getRuntime().exec("cmd /c cls");
        Runtime.getRuntime().exec("cmd /c echo "+sn+"| clip");
        System.out.println("S/N: ");   
        sn = entrada.next();
    }

1 answer

1


This response from Soen explains why your approach doesn’t work, but basically Runtime.exec redirects the standard output to a pipe which can be read by the Java process. Since the output was redirected, it is not applied to the console, and so it does not clean the screen of the same.

The same answer gives the solution: invoke the command with a ProcessBuilder and connect the output of the command with the output of the Java process, using inheritIO (method available from JDK 7):

new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

Thus, when the program is started on a console from the command line, the screen will be cleared.

  • 1

    Man, it worked perfectly!!! Thank you very much! I’ve been looking for the solution for some time. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.