Java run command in ALREADY RUNNING CMD window
I am creating a little program to take away some of my work by using a GUI. What I have right now is a little program with a button "Start" which starts a CMD-based application. What I need to do is enter a certain command in that开发者_StackOverflow CMD window. I want to add a button which fills out this command for me.
Is this even possible?
P.S.: CMD is Windows's Command Prompt.
Thank you all.
This works if it is an external command:
String command = "cmd"; //Replace with your command
Runtime.getRuntime().exec(command);
If it is an internal command then that will not work, but there is a workaround: create a batch file with the commands in it, and put a String with the path to the batch file as an argument.
Runtime.getRuntime().exec("Temp.bat");
Or you can write the batch file programmatically using this method:
private void batch(String commands){
try{
String filename = "Temp.bat";
File f = new File(filename);
PrintWriter writer = new PrintWriter(f);
writer.print(commands);
writer.close();
Runtime.getRuntime().exec(filename);
long x = getTime + 3000;
do{
//Wait
}while(getTime < x);
f.delete();
}catch(Exception ex){
ex.printStackTrace();
}
}
private long getTime(){
SimpleDateFormat datef = new SimpleDateFormat("yyyyDDDHHmmssSSS");
Date date = new Date();
return Long.parseLong("" + datef.format(date));
}
It depends on how your CMD-based application receives its input.
If it receives input from the input stream of the CMD window, this article explains how to get a reference to the input stream and send messages to it: Java exec - execute system processes with Java ProcessBuilder and Process.
If your CMD window is running a command that doesn't take input, and you want to execute another command, then I think you would have to run your second command in a separate CMD process.
精彩评论