user3369719 user3369719 - 3 years ago 130
Java Question

How do we take command line arguments using arg[] from intellij/eclipse

I was asked to run a program using command line arguments. The command line argument could either be a file or stdin.
eg:

Your program must accept input from two sources: a filename passed in
command line arguments and STDIN. For example './program input.txt' and './program < input.txt' should work.

Let me be frank, I am not sure whether I am being asked to pass the location of the file or feed the input to the program using STDIN. I am assuming, for now, it's asking me to input the location of the file. How can I do it using arg[0]? Can I use System.in, will that violate the requirement that is being asked from me?

Answer Source

I am not sure whether I am being asked to pass the location of the file or feed the input to the program using STDIN

Both. As stated, "your program must accept input from two sources". So, your program must support both, either taking a file argument or reading from standard in.

For the first variant, the file argument, the file's name will be available in arg[0].

So, if the arg-array contains at least one entry, go with the file argument. If there is no file argument (arg.length == 0), then read from STDIN.

In code, it could look a bit like this:

public static void main(String[] arg) {
  if (arg.length == 0) {
    // work with System.in
  } else {
    File file = new File(arg[0]);
    // work with file
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download