-3

In Windows you can start .exe files with certain parameters to do certain tasks like:

shutdown.exe -s

Is there anything like this in Java, I know that I can make a terminal input with a Scanner function, but what if I want to start the application invisible/not from at terminal but still be able to tell the application something.

DMK
  • 2,448
  • 1
  • 24
  • 35
deni
  • 119
  • 1
  • 1
  • 11

2 Answers2

1

Look at this Program:

public class Example {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

and call it like this:

java Example foo bar baz

Output will be

foo
bar
baz

You can also setup the command line arguments passed to the program in Eclipse under Run > Run Configurations > Arguments

jlordo
  • 37,490
  • 6
  • 58
  • 83
0

I would suggest using args4j.

All Java programs allow for command-line inputs through the main method:

public void main(String[] args)

But args4j allows you to easily create a class and parse flags something.exe -f flag1:

public class MyOptions {

    @Option(name="-r",usage="recursively run something")
    private boolean recursive;

    @Option(name="-o",usage="output to this file")
    private File out;

    @Option(name="-str")        // no usage
    private String str = "(default value)";

    @Option(name="-n",usage="usage can have new lines in it\n and also it can be long")
    private int num;

    // receives other command line parameters than options
    @Argument
    private List arguments = new ArrayList();
}

And you just have to call this class from your main method:

public void main(String[] args) throws IOException {
    MyOptions bean = new MyOptions()
    CmdLineParser parser = new CmdLineParser(bean);
    parser.parseArgument(args);
    // ...
}
john_science
  • 6,325
  • 6
  • 43
  • 60