Java Process getInputStream vs. getOutputStream
I'm a bit confused about 开发者_StackOverflow中文版the streams... which is which?
Simply, which stream should I use to catch the output of my Process, and which stream should I use to give my Process some input?
You can only read from an InputStream
, so use that to catch the output of your process.
You write to an OutputStream
, so use that to give the process your input.
You are using names that make sense in the context of the spawned process. But the API names make sense in the context of the parent process.
Here's another tip: if your process writes to standard error, be sure to read that too. If standard output or error pipes of the sub-process are full (because your parent Java process isn't consuming them), the child process will block on its write()
calls.
I always ignore the names and look at what's returned. If your code has an OutputStream
, you can write to it - which means it's the input for the other process. If your code has an InputStream
, you can read from it - which means it's the output or error for the other process.
Fortunately, the compiler will tell you if you're doing the wrong thing - you've got the data you want to provde, so you've got to write it to the stream, which means it's got to be the OutputStream
.
The getOutputStream is input to the process. The getInputStream is output read from the process.
Refer to the JavaDocs if it's helpful.
Look at the doc. This is indeed completely messing around, compared to other framework that make it in the "obvious" way, so the doc is your friend.
public abstract OutputStream getOutputStream()
> Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process
Should have been too simple to have:
public abstract InputStream getInputStream()
> Gets the standarinput stream of the subprocess. Output to the stream is piped into the standard input stream of the process
精彩评论