Java - communicating with a sub app through the input stream
Is there a way I can start a command-line application from java and then send strings (commands) to its input stream and display its response from its output stream?
I'm using an application with a pretty sophisticated command line interface (vlc). The application has an interpreter that responds to a set of commands. For example, after I start the app, I can start or stop a movie by issuing the command 'pause' on the command line.
I'd like to write a java application that executes the program and issues commands to the program. I've seen many examples of java apps starting an application and getting the output stream of开发者_开发问答 the app displaying the output of the app. But I've never seen an example, in which the java app would send requests to the sub-application.
Is there a way I can do this using java?
Thanks in advance!
So long as the spawned process listens on stdin for input, sure.
You'd launch a Process in the usual way (Runtime.exec()
) - I won't document it here, as you say you've seen plenty of examples.
Then once you have a handle to the spawned process, you call the confusingly-named getOutputStream. This gives you an OutputStream
, the other end of which is connected to the process' standard input. Hence, any bytes written to this stream can be consumed by your child process, just as if you were typing/piping input from a console.
I will point to a couple of resources that are always worth reading when dealing with Processes; cut-and-paste jobs from arbitrary Google results often don't cover the edge cases properly and can lead to deadlocks:
- When Runtime.exec() won't (old, but still relevant)
- Five common Java Process pitfalls
精彩评论