Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you keep the command prompt open when using Java?

Here's my code:

import java.io.*;

public class PingTest
{
    public static void main (String [] args) throws IOException, InterruptedException
    {
        Runtime.getRuntime().exec(new String[]
           {"cmd","/k","start","cmd","/c","ping localhost"});
    }
}

It pings the localhost like I want it to, but it doesn't stay open. It closes right away once it's done. What do I do to fix that?

like image 329
Samuel Bauer Avatar asked May 15 '26 19:05

Samuel Bauer


2 Answers

Since you're basically executing

cmd /k start cmd /c ping localhost

It does exactly what it should, runs start which runs cmd which terminates after ping finishes because of the /c flag.

If you want the window with the ping results to stay open you need to do

cmd /k start cmd /k ping localhost

or

cmd /c start cmd /k ping localhost

(Doesn't matter what the flag on the first cmd is because it isn't opening a new window.)

like image 166
trutheality Avatar answered May 17 '26 10:05

trutheality


One cheap fix is to request input at the end of main().

public static void main (String [] args) throws IOException, InterruptedException
{
    ...

    System.out.println("Press return to continue.");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
}
like image 27
Andy Thomas Avatar answered May 17 '26 08:05

Andy Thomas