public static void main(String[] args) { ... }
args
array contains the parameters from the command line. In your example the filename would be args[0]
. Beware however that if you hard code args[0]
into your code, then don't pass a parameter, you will get an ArrayIndexOutOfBoundsException
because args[0]
doesn't exist.
You can expand this to include multiple parameters if you need to. For example
java myprogram configfile.txt configfile2.txt configfile3.txt
Those filenames would be args[0]
args[1]
and args[2]
respectively.
If your program can run with or without arguments, you can find out if you have some by checking the length of the array is > 0. Something like
if (args.length > 0) { myfile = args[0]; }
else { myFile = someDefaultFilename; }
or if you can have multiple parameters you can loop through the entire array
for (String s : args) { //Do something with each parameter }