Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run interactive command line application from java

Tags:

java

process

I normally use java.lang.ProcessBuilder and java.lang.Process to run external command line programs, and it works fine for run-and-done commands. For example, this would run "myProgram" with argument "myArg" in the working directory:

List<String> commandLine = new ArrayList<String>();
commandLine.add("myProgram");
commandLine.add("myArg");
ProcessBuilder builder = new ProcessBuilder(commandLine);
builder.redirectErrorStream(true);
Process process = builder.start();

However, say I wanted to run a script or program or something that had interactive input (it prompted me for more input after starting). Can I do that in Java with code similar to that above, or do I need a different approach? Or is there some library that can help me with this?

like image 932
smcg Avatar asked Sep 11 '12 19:09

smcg


People also ask

Can Java run CMD?

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.


1 Answers

According to the documentation you should be able to redirect the input and output streams. This tells it to use the System.in/System.out from the parent process:

builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

If you want to write things to the processes's input:

If the source is Redirect.PIPE (the initial value), then the standard input of a subprocess can be written to using the output stream returned by Process.getOutputStream(). If the source is set to any other value, then Process.getOutputStream() will return a null output stream.

like image 63
Brendan Long Avatar answered Oct 09 '22 10:10

Brendan Long