从 Java 执行 cmd.exe 命令 [英] Executing cmd.exe commands from Java

查看:36
本文介绍了从 Java 执行 cmd.exe 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to read a file from the user, in which each line is a cmd.exe command, 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:

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

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

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

I'm trying to run the commands like this:

Runtime.getRuntime().exec(command);

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

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

推荐答案

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

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

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

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

cmd.exe /c echo hello

这篇关于从 Java 执行 cmd.exe 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆