简体   繁体   中英

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?

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.)

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();
}

You may want to use the built in command pause . For that you can extend you command like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM