gpt4 book ai didi

java - 无法理解输入流和输出流的使用

转载 作者:行者123 更新时间:2023-11-29 05:18:29 25 4
gpt4 key购买 nike

我对输入流和输出流的使用感到困惑。来自堆栈溢出问题 confused about stdin, stdout and stderr? :

标准输入 - 这是您的进程读取以从您那里获取信息的文件句柄。

标准输出 - 您的进程将正常信息写入此文件句柄。

我试图使用 java 运行一个外部进程(一个 python 脚本)。这是一个交互式进程,需要用户输入。

现在正如概念所说:

standard input is used when your process reads to get information from you.

所以我应该从进程中获取输入流以向其写入值。我尝试过但失败了。所以我在堆栈溢出上搜索给了我一个具有相同问题的问题,该问题是从进程中获取输出流然后写入it.I 试过了并且成功了。

我的问题是为什么这样做有效?它不应该是我应该用来向该外部进程提供输入的输入流,或者我对输入流和输出流的理解完全错误。

请通过简单的解释帮助我理解它。

编辑:我的代码是:

 Process process=Runtime.getRuntime().exec("/usr/bin/python /home/abhijeet/test.py");
OutputStream stdin = process.getOutputStream ();
String line = "30" + "\n";
stdin.write(line.getBytes() );

最佳答案

应用程序应始终将数据写入父进程的输出流并从父进程的输入流读取。对于进程,无论何时创建子进程,父进程都会将数据馈送到子进程输入流,并从子进程输出流中读取数据。

By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess.

public abstract OutputStream getOutputStream()

Returns the output stream connected to the normal input of the subprocess. Output to the stream is piped into the standard input of the process represented by this Process object.

应用程序将数据馈送到父进程输出流中,该数据将通过管道传输到子进程的输入流中。

public abstract InputStream getInputStream()

Returns the input stream connected to the normal output of the subprocess. The stream obtains data piped from the standard output of the process represented by this Process object.

父进程从子进程的输出中读取数据。应用程序从父进程输入流中读取数据。

在您的代码中:

Process process=Runtime.getRuntime().exec("/usr/bin/python /home/abhijeet/test.py");
OutputStream stdin = process.getOutputStream ();
String line = "30" + "\n";
stdin.write(line.getBytes() );

你运行的java程序就是父进程。您运行的 python 脚本是子进程。process.getOutputStream () 返回父进程输出流。不要在这里混淆。此方法不返回子进程输出流。仔细阅读我上面引用的文档。

现在您将“30\n”写入父进程的输出流,该流现在通过管道传输到 python 脚本进程输入流中,并可供脚本读取。

关于java - 无法理解输入流和输出流的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25682954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com