[英]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. 它像我想要的那样ping localhost,但它不会保持打开状态。 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. 它完全应该运行,运行
start
运行cmd
,由于/c
标志, ping
完成后终止。
If you want the window with the ping results to stay open you need to do 如果您希望具有ping结果的窗口保持打开状态,则需要执行此操作
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.) (第一个
cmd
上的标志是什么并不重要,因为它没有打开一个新窗口。)
One cheap fix is to request input at the end of main(). 一种便宜的解决方法是在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
. 您可能要使用内置的命令
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\""});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.