windows 从 Java 执行 cmd.exe 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4031390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:29:27  来源:igfitidea点击:

Executing cmd.exe commands from Java

javawindowscmd

提问by Amir Rachum

I'm trying to read a file from the user, in which each line is a cmd.execommand, and run it (it's okay to assume the commands are legal), but when I give a command like echo hi, I get runtime exception error:

我试图从用户那里读取一个文件,其中每一行都是一个cmd.exe命令,然后运行它(假设命令是合法的就可以了),但是当我给出类似的命令时echo hi,我得到运行时异常错误:

Exception in thread "main" java.io.IOException: Cannot run program "echo": CreateProcess error=2, The system cannot find the file specified

线程“main”中的异常java.io.IOException:无法运行程序“echo”:CreateProcess error=2,系统找不到指定的文件

I'm trying to run the commands like this:

我正在尝试运行这样的命令:

Runtime.getRuntime().exec(command);

where command = "echo hi". This does work for commands like regeditthough, so it seems the runtime I'm getting is like the "run" window and not cmd. Is there a way to run these commands?

哪里command = "echo hi"。这确实适用于类似的命令regedit,所以看起来我得到的运行时就像“运行”窗口而不是 cmd。有没有办法运行这些命令?

回答by paxdiablo

That's because echois not an external executable command (i.e., there is no echo.exefile on your hard disk, unless you put it there yourself). It's an internal command of the shell.

那是因为echo不是外部可执行命令(即,echo.exe您的硬盘上没有文件,除非您自己将其放在那里)。这是shell的内部命令。

You'll probably find that you need to execute something like:

您可能会发现需要执行以下操作:

cmd.exe /c echo hello