Java 进程 getInputStream 与 getOutputStream
我对流有点困惑......哪个是哪个?
简而言之,我应该使用哪个流来捕获进程的输出,以及应该使用哪个流来为我的进程提供一些输入?
I'm a bit confused about 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只能从
InputStream
中读取,因此请使用它来捕获进程的输出。您写入
OutputStream
,因此使用它为进程提供输入。您使用的名称在生成的进程的上下文中有意义。但 API 名称在父进程的上下文中有意义。
这是另一个提示:如果您的进程写入标准错误,请务必也阅读该内容。如果子进程的标准输出或错误管道已满(因为父 Java 进程没有使用它们),则子进程将阻塞其
write()
调用。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.我总是忽略这些名字并查看返回的内容。如果您的代码有一个
OutputStream
,您可以写入它 - 这意味着它是其他进程的输入。如果您的代码有一个InputStream
,您可以从中读取 - 这意味着它是其他进程的输出或错误。幸运的是,编译器会告诉您是否做错了 - 您已经获得了想要提供的数据,因此您必须将其写入流,这意味着它已经得到了成为
OutputStream
。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 anInputStream
, 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
.getOutputStream 是进程的输入。 getInputStream 是从进程读取的输出。
如果有帮助,请参阅 JavaDocs 。
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.
Should have been too simple to have: