0

I am looking at starting a program on the command line as normal. (i.e java myprogram)

However I know it's possible to type

  java myprogram configfile.txt 

so it takes this string and later on in the code I can use it to load a file.

How do I capture this input in the program using something like a constructor if possible.

chostwales
  • 89
  • 2
  • 9

1 Answers1

4
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 }
takendarkk
  • 3,347
  • 8
  • 25
  • 37