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

查看:457
本文介绍了从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);

其中 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天全站免登陆