I'm making an application that is mainly used with pipes. At the start of the program, here is how I get all my input:
Scanner scanner = new Scanner(System.in);
List<String> input = new ArrayList<>();
while (scanner.hasNextLine()) {
input.add(scanner.nextLine());
}
scanner.close();
When used with pipes, this works well. For example, running ls | java -jar ...
it prints out all the lines given from ls
. However, when I just run java -jar ...
with no input/pipe, it freezes and nothing happens. Even when I press enter and mash my keyboard it's still stuck. I can only stop the program by using ctrl-c. I think this is because there is nothing to read so Scanner waits until there is something to read. How do I read all lines from System.in
without freezing, or is there a better way to do this? Thanks.
Edit:
Whoever marked this as a duplicate clearly did not read my question. My question was to check if the System.in
was empty to not freeze the program, not how to get past the input stage. It is freezing because there is nothing in System.in
so Scanner is taking forever, but I want to check if there is nothing in System.in
.
Answer: Thank you @QiuZhou for the answer. I modified his second example to get this:
List<String> input = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (reader.ready()) {
String nextLine = reader.readLine();
input.add(nextLine);
}
and it works like a charm.