在Java中将各种字符串输入到同一进程 [英] Input various strings to same process in Java

查看:73
本文介绍了在Java中将各种字符串输入到同一进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Java 程序,它通过 ProcessBuilder 访问已编译的 C++ 程序.C++ 程序需要一段时间才能启动",但是一旦启动,它就可以接收文本字符串并非常快速地获得输出(当前正在写入文本文件).

I am writing a Java program which accesses a compiled C++ program via a ProcessBuilder. The C++ program takes a while to "start up", but once it has done so, it can take in strings of text and get an output (currently being written to a text file) very quickly.

从本质上讲,有没有办法让正在运行的进程等待"给它一个输入,而不是在它启动时输入输入源?我不想每次用户输入字符串时都必须重新启动进程,因为这将花费太长时间并且是不必要的.同时,我想启动这个过程,让它准备好",然后提示用户输入.一旦用户这样做,我想将该输入发送到正在运行的进程,收集输出并呈现出来.可以这样做吗?

Essentially, is there a way to have a running process "wait" for an input to be given to it, rather than have to enter the input source as it is started? I don't want to have to restart a process every time a user inputs a String, as that will take too long and is unnecessary. At the same time, I want to start the process, have it "ready", and then prompt the user for an input. As soon as the user does so, I want to send that input to the running process, collect the output, and present that. Is this possible to do?

谢谢!

推荐答案

如果您希望 Java 程序等待"C++,您需要某种方式让 C++ 程序告诉 Java 程序它已准备就绪.您可以通过从 C++ 程序的输出流向 Java 程序发送消息来实现这一点,并让 Java 程序等待,直到它在它自己的输入流上读取某些内容,然后才提示用户输入.

If you want the Java program to "wait" for the C++, you need some way for the C++ program to tell the Java program that it is ready. You could do this by sending a message from the C++ program's output stream to the Java program, and have the Java program wait until it reads something on it's own input stream before it prompts the user for input.

另一方面,您的 Java 程序等待的唯一原因是装饰性的.如果您的所有通信都通过流进行,则 Java 程序可以随时开始向 C++ 发送字符串,一旦完成启动,C++ 将从其输入流中读取这些字符串.没有 Java 程序等待意味着用户输入和接收输出之间的时间可能会更长,但启动 C++ 程序和接收输出之间的总时间实际上可能会减少.

On the other hand, the only reason for your Java program to wait is cosmetic. If all your communication is happening over streams, the Java program can start sending strings to the C++ at any time, and the C++ will read those strings from its input stream once it finishes starting up. Not having the Java program wait means the time between user input and received output might be longer, but the total time between starting up the C++ program and receiving the output may actually be reduced.

这篇关于在Java中将各种字符串输入到同一进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆