Java: Read file from stdin then prompt user for input

孤者浪人 提交于 2019-12-11 18:27:18

问题


I'm writing a Java program that reads a file from stdin and then prompts the user for interactive input. It should be executed like:

cat file.txt | java -jar myprog.jar
#
# ...Read file.txt then prompt user:
#
Some input please: 

The problem is that after reading file.txt, the stdin seems "used up" and I don't know how to restore it to get user's input. Here's an example of what I'm trying to do:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        String line;
        while((line = br.readLine()) != null) {
            // Do something with line
            System.out.println(line);
        }
        br.close();

        Scanner scanner = new Scanner(System.in);
        String input= scanner.nextLine();

    }
}

When I executed it, I get:

echo -e "foo\nbar\nbaz" | java -jar biojava-tmp.jar 
foo
bar
baz
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at biojava_tmp.Main.main(Main.java:21)

How can I resolve this?


PS: In my real program I don't use Scanner, instead I use jline as below but I figure the problem is the same.

ConsoleReader console= new ConsoleReader();
console.readLine()

来源:https://stackoverflow.com/questions/56316100/java-read-file-from-stdin-then-prompt-user-for-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!