Reputation: 1
In Java I want to create a CMD process and send inputs to it and then output the information that is displayed in the process. Are there any external jars that would allow me to do this?
I have tried using Runtime but I can only run the maximum of one command at a time before the process is closed.
Runtime rt = Runtime.getRuntime();
{
public static void main(String[] args)
{
try
{
// We are running "dir" and "ping" command on cmd
Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"dir && ping localhost\"");
}
catch (Exception e)
{
System.out.println("HEY Buddy ! U r Doing Something Wrong ");
e.printStackTrace();
}
}
}
I need it so the command prompt remains open as I will be running an exe file which outputs different information depending what commands are input.
Upvotes: 0
Views: 95
Reputation: 1734
You could use ProcessBuilder in a loop and inherit IO. This should write the output of the process to the same location as the calling process. In this case probably the console.
For more information see: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
You could try something like following:
public static void main(String[] args){
List<String> commandArguments = new ArrayList<>();
while(someCondition){
commandArguments.add("cmd.exe");
commandArguments.add("/C");
commandArguments.add(yourCommands); //Read input from console
executeCommand(commandArguments)
}
}
private void executeCommand(List<String> commandArguments){
if(commandArguments != null){
try{
new ProcessBuilder(commandArguments).inheritIO().start().waitFor();
}catch(IOException, InterruptedException ex){
ex.printStacktrace();
}
}
}
Upvotes: 1