mewi
mewi

Reputation: 352

Can't get stdin to read into array on linux - Java

So I'm using Java on a Linux machine and I currently am trying to read from stdin so that when I run "java Simulation more ~test/locationOfInput/test" it takes a stream of numbers and calculates values and prints them. However, my code is locking up when trying to read in the values and I have a check for empty files so I know it's at least receiving the file. I currently have this code to read the stdin into an array

    Scanner input = new Scanner(System.in);
    ArrayList<Integer> values = new ArrayList<Integer>();

    while (input.hasNextInt()) {
        int i = input.nextInt();
        values.add(i);
    }

The loop seems to be running infinitely and I'm not sure why. Am I misunderstanding how to read in from STDIN?

Upvotes: 1

Views: 197

Answers (2)

daniu
daniu

Reputation: 15008

You need to use cat ~test/locationOfInput/test | java Simulation to redirect the output properly.

Upvotes: 1

jrtapsell
jrtapsell

Reputation: 7031

You have 2 options:

  1. Pipe the input into the program as @daniu suggested
  2. Take the file path as an argument and read from the file with the given path

You could implement both in 1 program, so if it has an argument it reads from that file, otherwise it would read from piped input.

Upvotes: 0

Related Questions