Monday 16 September 2013

Eclipse tip : work around for the < argument

This post is a quick tip on Eclipse usage. Suppose you are running a java application that reads in a file whose name is supplied at the command line with the < operator. This idiom is used in Algorithms Fourth Edition by Robert Sedgewick and Kevin Wayne.
Example : java TopM 5 < tinyBatch.txt

The code to process the data in tinyBatch.txt is :
while (StdIn.hasNextLine()) {

}

The problem comes when you run the programs in Eclipse or in the Eclipse-based STS.
You can specify command line arguments via Right Click --> Properties --> Run/Debug Settings --> Edit -> Arguments -> Program Arguments. However, if you give < as a command line argument, the program waits for input, which you have to paste from your file into the console. This is not clean.

Fortunately there is a work around. You setIn the command line argument and your file processing code works properly. Here's how you do it:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
try {
    System.setIn(new FileInputStream(args[1]));
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}

Now you just give the filename as argument without the <.That is, java TopM 5 tinyBatch.txt
while (StdIn.hasNextLine()) {
works as usual.

No comments:

Post a Comment