首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用bash将输入通过管道传送到Java程序

如何使用bash将输入通过管道传送到Java程序
EN

Stack Overflow用户
提问于 2011-04-20 09:37:55
回答 5查看 28.6K关注 0票数 26

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

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传递到这个程序。我尝试了以下几种方法:

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

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

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

编辑2:

看起来我遇到了与此操作相同的问题:Command Line Pipe Input in Java

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

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-04-20 10:13:13

修好了。在输入管道完成后,readLine()一直返回null,因此无限循环继续循环。

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

票数 5
EN

Stack Overflow用户

发布于 2012-08-29 18:17:23

你有while(true),所以你会得到无限循环。

在循环中的某处添加break是修复该问题的一种方法。但这不是一种好的风格,因为读者必须在循环中寻找,以找出它是否以及何时退出。

最好让您的while语句清楚地显示退出条件是什么:

String inputStr = "";
while(inputStr != null) {
    inputStr=bufReader.readLine(); 
    if(inputStr != null) {
        ...
    } else {
        System.out.println("inputStr is null");
    }
}
票数 7
EN

Stack Overflow用户

发布于 2014-04-25 00:05:21

我喜欢斯利姆的回答,只是我的处理方式有点不同。这是我用来逐行阅读文本流的基本模板。

try {
    // Wrap the System.in inside BufferedReader
    // But do not close it in a finally block, as we 
    // did no open System.in; enforcing the rule that
    // he who opens it, closes it; leave the closing to the OS.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;
    while ((line = in.readLine()) != null) {
        // TODO: Handle input line
    }

    // Null was received, so loop was aborted.

} catch (IOException e) {
    // TODO: Add error handler
}

如果我正在读取一个文件,我会稍微修改一下,以关闭文件,如下所示

try {
    File file = new File("some_file.txt");

    // Wrap the System.in inside BufferedReader
    // But do not close it in a finally block, as we
    // did no open System.in; enforcing the rule that
    // he who opens it, closes it; leaves the closing to the OS.
    BufferedReader in = new BufferedReader(new FileReader(file));
    try {
        String line;
        while ((line = in.readLine()) != null) {
            // TODO: Handle input line
        }

        // Null was received, so loop was aborted.

    } finally {
        try {
            in.close();
        } catch (IOException e) {
        }
    }

} catch (IOException e) {
    // TODO: Add error handler
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5724646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档