如何使用bash将输入传递给Java程序 [英] How to pipe input to Java program with bash

查看:167
本文介绍了如何使用bash将输入传递给Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java程序正在监听标准输入:

My Java program is listening on standard input:

InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bufReader = new BufferedReader(isReader);
while(true){
    try {
        String inputStr = null;
        if((inputStr=bufReader.readLine()) != null) {
            ...
        }
        else {
            System.out.println("inputStr is null");
        }
    }
    catch (Exception e) {
        ...
    }
}

现在,我想从bash管道输入到这个程序。我尝试了以下内容:

Now, I want to pipe input to this program from bash. I tried the following:

echo "hi" | java -classpath ../src test.TestProgram

但它只是打印 inputStr为null 无限次。我做错了什么?

But it's just printing inputStr is null infinite times. What am I doing wrong?

编辑1:更新了问题以包含更多代码/上下文。

Edit 1: Updated question to include more code / context.

编辑2:

看起来我遇到的问题与此OP相同: Java命令行管道输入

Looks like I'm experiencing the same issue as this OP: Command Line Pipe Input in Java

如何修复程序,以便我可以输入管道进行测试,但正常运行程序将允许用户输入标准输入的输入?

How can I fix the program so that I can pipe input in for testing, but running the program normally will allow users to enter input on standard input as well?

推荐答案

修正了它。输入管道完成后, readLine()保持返回 null ,因此无限循环保持循环。

Fixed it. After the piping of input was completed, readLine() kept returning null, so the infinite loop kept looping.

修复是在 readLine()返回null时从无限循环中断。

The fix is to break from the infinite loop when readLine() returns null.

这篇关于如何使用bash将输入传递给Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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