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()