Instead of hard coding to read the infile
and outfile
, I want to read from the command line. How would I do that?
/**
* reads a file and creates a histogram from it
* @param args string of argument
* @precondition none
*/
public static void main(String[] args) {
Histogram hist = new Histogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords("infile.txt");
output.writeWords("outfile.txt");
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
public static void main(String[] args) {
WordHistogram hist = new WordHistogram();
FileInputController input = new FileInputController(hist);
FileOutputController output = new FileOutputController(hist);
try {
input.readWords(args[0]); //args[0] is the first argument passed while launching Java
output.writeWords(args[1]); //args[1] is the second argument passed while launching Java
} catch (FileNotFoundException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} catch (IOException exception) {
System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
} finally {
System.exit(1);
}
}
Run your program like: java YourClassName infile.txt outfile.txt
In main(String[] args)
, args
is an array of Strings which contains values of arguments passed while launching Java.
Please DO read Oracle docs about command line arguments for further reading.