Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

process - run interactive command line application from java

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...