The ultimate goal of the project I'm currently working on is to create a Swing command prompt which uses Window's Cmd prompt to execute commands. I have the swing portion finished, now I just need to stream input/output between my Java program and the command prompt.
Now I want the underlying functionality of this command prompt to be fairly similar to what the real thing will do (granted with a few exceptions, these are kind of irrelevant in this topic), which involves supporting stuff like batch files and the set command.
It isn't a problem to get one single command to work (or even running a bunch of commands in a batch file), but I'm having problems getting multiple user-entered commands to work.
For example:
SET IS_OK=1 IF IS_OK EQU 1 (ECHO "It is ok.") ECHO "DONE"
The expected output if a user were to type this into a real command prompt would be to print out "It is ok.", followed by "DONE" (without quotes)
The way I currently have it setup is to run a new command prompt for every command. This automatically dis-allows the above from working because set only works in an individual's environment variable.
Here's a short example of what I'm doing:
import java.io.IOException; import java.util.Scanner; public class Test { public static void main(String[] args) throws IOException, InterruptedException { runWndCommand("SET IS_OK=1"); runWndCommand("IF IS_OK EQU 1 (ECHO It is ok.)"); runWndCommand("ECHO DONE"); } /** * runs a Windows command prompt with the given command. Output is printed * out to System.out. Not entirely robust, but it demonstrates the point. * * @param cmd * @throws IOException * @throws InterruptedException */ public static void runWndCommand(String cmd) throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(new String[] { "cmd.exe", "/C", cmd }); Scanner reader = new Scanner(p.getInputStream()); while (reader.hasNext()) { System.out.println(reader.nextLine()); } p.waitFor(); } }
The output of this code is to only print out "DONE"
Before you start saying that I could pass multiple commands in the runtime.exec() call, remember that this is for a command prompt. As such, individual calls are very likely to be executed before the next command would even be entered.
Is something like this even possible to do (without resorting to JNI, JVM mods, etc.)?
I've tried piping input to the command process using p.getOutputStream() (and running the command prompt without the /C flag), but the command prompt doesn't seem to respond to any inputs I put through this stream.
Oh, and I would really prefer not to re-write the windows command prompt functionality all in Java.
cross-posted at Cmd process streams - Java Forums.