Command Line Arguments in Eclipse

Before we go on to JUnit testing, let’s cover another tricky situation in Eclipse: how do we use command line arguments from within a graphical IDE? You might have noticed that my class has methods to read strings from a text file and write strings to a new text file, but we haven’t tested them yet. Let’s re-write the main method to read as follows:

public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("\nYou must specify the input and output file " +
                    "paths!\n\nExample: SortedStringList input.txt ouput.txt" +
                    "\n\n");
            System.exit(1);
        }
        SortedStringList list = new SortedStringList(args[0]);
        list.printToFile(args[1]);
        System.out.printf("\nResults written to: %s\n\n", args[1]);
    }

Be sure to save the file. Next, we’ll need an input file to use as an example. Here’s one I came up with:

input.txt

Whiskey
Oscar
Quebec
Delta
X-Ray
Sierra
Mike
Hotel
Uniform
Juliet
Tango
Lima
India
November
Golf
Bravo
Romeo
Yankee
Zulu
Papa
Victor
Charlie
Foxtrot
Echo
Alpha
Kilo

Now let’s see how this would work from the terminal. Let’s say the path to your input.txt file is input_path. Recompile your java bytecode and run the program again like this:

$ javac path/SortedStringList.java
$ java -cp path SortedStringList input_path/input.txt input_path/output.txt

Results written to: input_path/output.txt

Leave a Reply

Your email address will not be published.