Kevin
Kevin

Reputation: 16013

Run Java program by giving it input using file redirection

I'm trying to run a Java program using file redirection. I'm testing it with this simple program:

package netbeans.sanbdox;

public class Sanbdox {
    public static void main(String[] args) {
        for(int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

When I go to the command line and run

$ java -jar dist/compiled_project.jar < q1.txt
$ 

There's no output, even though q1.txt is not an empty file. What should I do to make the file redirection work?

Upvotes: 5

Views: 18099

Answers (2)

The Coordinator
The Coordinator

Reputation: 13137

The input is captured by the System.in and not as data passed through the main(String[] args) method when the program starts.

To read that data from the input, read it from System.in as an InputStream or wrap it in a Reader:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

... s.readLine() 

And make sure to not close the System.in or the Reader, or else you will close keyboard input to your program too!

Upvotes: 4

Chris Hayes
Chris Hayes

Reputation: 12050

Redirecting in that form just replaces stdin with a file stream coming from that file. Your code does not use stdin for anything, therefore you won't have any output, since you aren't passing any command line arguments to the program.

To see what you're expecting, you'd have to use a Scanner:

Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

scanner.close(); // Not required for stdin but good practice

If what you really wanted was to have each token from the file supplied as a command line argument, you could do something like this in your shell:

$ java -jar dist/compiled_project.jar $(cat q1.txt)

That would output the contents of q1.txt as part of the shell command. Odds are it won't work the way you want due to newline characters or other concerns.

Upvotes: 10

Related Questions