wujido
wujido

Reputation: 139

Don't close stdin after initial value was processed in Java

I am making simple console app. My main loop looks like this.

var s = new Scanner(System.in);
while (appShouldRun) {
    var action = s.nextLine();
    // proccess action
}

It works fine when I run app with empty stdin.

java -jar app.jar

But I want to have some prepared scenarios in file. Run them and then wait for next user input.

Expected behaviour:

java -jar app.jar < scenario.txt

output of commands from file

| <- cursor, waiting for user input
// scenario.txt

cmd1
cmd2
cmd3
.
.
.

Problem is that when I run program with something od std in, it process commands correctly, but then it throws

java.util.NoSuchElementException: No line found

I think it's becouse stdin is closed after all lines from file is processed. Am I wrong? How to fix the code to get expected behaviour?

Thanks

Upvotes: 0

Views: 289

Answers (2)

nin2h
nin2h

Reputation: 11

I have tried do change as little code as possible. This reads the whole file like you wanted and ends without Exception

public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        boolean appShouldRun = true;
        while (appShouldRun) {
            String action = s.nextLine();
            System.out.println("got: " + action);
            appShouldRun = s.hasNext();
        }
    }
}

Upvotes: 0

Matt Timmermans
Matt Timmermans

Reputation: 59263

When you redirect standard input with <, it is connected to the input file, and not connected at all to the console.

If you want your program to receive input on the console, then you can't redirect stdin. You should take the filename as a command-line argument instead. Open it, read it, close it, and then process stdin.

OR, if you really want to, and you're on a unix/linux/macOS system, you can run it like this, using the cat command to concatenate standard input to something else:

cat scenario.txt - | java -jar app.jar

Upvotes: 1

Related Questions