[英]How do you continuously input from Java program to EXE's console?
I have an EXE file, addOne.exe
which continuously gets an integer input from the user on the console (NOT command line parameters) and outputs the integer + 1 onto the console . 我有一个EXE文件
addOne.exe
,它不断从控制台上的用户获取整数输入(NOT命令行参数) ,并将整数+ 1输出到控制台。 Sample output is shown below: 示例输出如下所示:
1
2
6
7
29
30
...
I have already made the EXE outputs work, that is, Whenever the EXE outputs text to the console, print that text from the Java program . 我已经使EXE输出工作,也就是说,只要EXE将文本输出到控制台,就从Java程序中打印该文本。 I am trying to:
我在尝试着:
Scanner.nextInt()
and input to the EXE as console input Scanner.nextInt()
从Java程序获取用户输入 ,并作为控制台输入输入到EXE Currently, I have the following code: 目前,我有以下代码:
Process process = Runtime.getRuntime().exec("D:\\addOne.exe");
...
Scanner keyboard = new Scanner(System.in);
String input = "";
OutputStream stdin = process.getOutputStream();
while (!input.equals("exit")) {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin))) {
input = keyboard.nextLine();
writer.write(input);
} catch (IOException ex) {
Logger.getLogger(CmdLineTest.class.getName()).log(Level.SEVERE,null,ex);
}
}
However, whenever I run this code, the first iteration of the while loop (the first time I input something) is able to send the input to the EXE, but after the first iteration, the error java.io.IOException: Stream Closed
is given. 但是,每当我运行此代码时,while循环的第一次迭代(第一次输入内容)都能够将输入发送到EXE,但是在第一次迭代之后,错误
java.io.IOException: Stream Closed
is给出。
How can I continue to get user input from a Scanner.nextInt()
inside a while loop 如何在while循环中继续从
Scanner.nextInt()
获取用户输入
Thank you. 谢谢。
Edit: writer.flush()
does not seem to input the user input from the Java program to the EXE. 编辑:
writer.flush()
似乎没有将用户输入从Java程序输入到EXE。
Edit: see my answer below 编辑:请参阅下面的答案
Switch the scope of your try
and while
statements so that you're only making 1 BufferedWriter
. 切换
try
和while
语句的范围,这样你只能制作1个BufferedWriter
。 When your try-with-resources code block ends, the writer is closed and by extension stdin
is as well. 当您的try-with-resources代码块结束时,编写器将被关闭,并且扩展名为
stdin
。 Thus no more writers can be made for that object. 因此,不能再为该对象制作作者。
try([resources]) {
while([condition]) {
...
}
} catch(IOException ex) {
...
}
It seems that using writer.flush() inputted the stream into the EXE, but the stream required a writer.newLine() before the input was processed by the EXE, as the console requires the enter key to be pressed after the input. 似乎使用writer.flush()将流输入到EXE中,但是在EXE处理输入之前,流需要writer.newLine(),因为控制台需要在输入后按下回车键。
Here is the working code: 这是工作代码:
while (true) {
try {
input = keyboard.nextLine();
writer.write(input);
System.out.println("IN: "+input);
writer.newLine();
writer.flush();
} catch (IOException ex) {
Logger.getLogger(CmdLineTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.