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.

2
  • 4
    Have you searched at all for getting Java command line input? Commented Nov 24, 2014 at 22:44
  • possible duplicate of Java Command line arguments Commented Nov 24, 2014 at 22:49

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for watchin my back.
How would I do the code to check if an argument was passed? If doing an if statement it throws this exception if (args[0]!=null){ filename = args[0]; }
I will add it to the answer.
@chostwales if (args.length == x) with x as the expected size.
You don't have to check the size of args if you use a for each loop. args won't be null and if it is empty, then this loop will be skipped without any problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.