Use the library Apache Commons CLI. It's a library there you can build OptionLists (arguments, parameters, etc.) like this.
package CLi;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public class CLi
{
/**
* @see http://www.thinkplexx.com/blog/simple-apache-commons-cli-example- java-command-line-arguments-parsing
* @see http://stackoverflow.com/a/10798945
* @see http://stackoverflow.com/questions/36166630/apache-commons-cli- not-parsing-as-expected
*
* Link to Java-Library:
* @see https://commons.apache.org/proper/commons-cli/
*/
/**
* Variables
*/
private String[] args;
private Options options = new Options();
private HelpFormatter formater;
private CommandLineParser parser;
private CommandLine cmd;
private Scanner console;
private String cmdLine;
private boolean noParam;
/**
* Constructor.
* @param args - The command-line arguments.
*/
public CLi(String[] args)
{
this.args = args;
buildCLIOptions();
}
public void parse() throws Exception
{
if(args.length == 0)
{
noParam = true;
args = scanParams();
}
else
{
try
{
parser = new DefaultParser();
cmd = null;
cmd = parser.parse(options, args);
/**
* Print help.
*/
if (cmd.hasOption("help"))
{
noParam = false;
help();
}
/**
* Shutdown.
*/
if (cmd.hasOption("exit"))
{
noParam = false;
System.exit(0);
}
}
}
}
/**
* @throws Exception
*/
public void help() throws Exception
{
/**
* This prints out some help
*/
formater = new HelpFormatter();
formater.printHelp("Main", options);
System.out.println(" ");
noParam = true;
scanParams();
}
/**
* Scan params.
* @return the Parameters
* @throws Exception
*/
public String[] scanParams() throws Exception
{
System.out.println("Ready... Waiting for input...:");
System.out.println(" ");
console = new Scanner(System.in);
while(noParam)
{
cmdLine = console.nextLine();
args = cmdLine.replace(" -", " #-").split(" #");
parse();
}
console.close();
return args;
}
public void buildCLIOptions()
{
options.addOption("exit", "exit", false, "Exiting application.");
options.addOption("help", "help", false, "show help.");
}
}
In the Main class do:
public class Main
{
public static void main(String[] args) throws Exception
{
CLi console = new CLi(args);
console.parse();
}
}