简体   繁体   English

打开cmd提示符并执行命令java

[英]opening cmd prompt and execute command java

I was able to open a command prompt from my Java program with the following code: 我可以使用以下代码从Java程序中打开命令提示符:

String cmd = "C:\\WINNT\\system32\\cmd.exe /c start";


    try {
        @SuppressWarnings("unused")
        Process ps = Runtime.getRuntime().exec(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }

The above code opens the command prompt. 上面的代码打开命令提示符。

If I want to execute some command in this opened command prompt , what I have to do? 如果要在此打开的命令提示符下执行某些命令,该怎么办?

ANy help is appreciated. 感谢您的帮助。

I think you are at the right direction. 我认为您的方向正确。 To execute some commands or more than one command, repeat the cmd /k [command] , like this:- 要执行某些命令或多个命令,请重复cmd /k [command] ,如下所示:-

// write dir output to file
Runtime.getRuntime().exec(new String[] {
        "cmd",
        "/k",
        "dir",
        ">",
        "c:\\output.txt"
});

// create test-dir folder in c:\
Runtime.getRuntime().exec(new String[] {
        "cmd",
        "/k",
        "mkdir",
        "c:\\test-dir"
});

我知道cmd /k [some other command]将在命令提示符下运行该命令,但它仅运行一个,因此这是一个有限的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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