Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

windows - Executing cmd.exe commands from Java

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:

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". 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...