Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing cmd.exe commands from Java

Tags:

java

windows

cmd

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?

like image 209
Amir Rachum Avatar asked Oct 27 '10 08:10

Amir Rachum


People also ask

Can Java run cmd?

We must follow the steps given below to run a Java program. Open the notepad and write a Java program into it. Save the Java program by using the class name followed by .java extension. Open the CMD, type the commands and run the Java program.

How do you execute a command in Java?

Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

How do I run cmd EXE?

Open the “File” menu and then choose “Run New Task.” Type cmd or cmd.exe , and then click “OK” to open up a regular Command Prompt. You can also check the “Create this task with administrative privileges” to open Command Prompt as administrator.


1 Answers

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
like image 135
paxdiablo Avatar answered Oct 14 '22 17:10

paxdiablo