====== Kommando Zeilen Parameter in Java mit der Apache Commons CLI library verarbeiten ====== Mit der Apache Java Library **Commons CLI** steht eine Bibliothek für das Parsen von Parametern für den Aufruf von Java Programmen zur Verfügung. Vorbereitung: Download der Jar Dateien: http://commons.apache.org/proper/commons-cli/download_cli.cgi Beispiel: Import: import org.apache.commons.cli.*; Optionen definieren: . .. ... // // zum Beispiel im Konstruktor der Klasse oder in einen static {} Konstrukt // // Mit Hilfe des OptionBuilder // Hilfreich bei Optionen mit Parametern Option minPWDAsciiCode = OptionBuilder.withArgName("31") .hasArg() .withDescription("Minimal dezimal ascii code for the password") .create("minAscii"); // Neue Option anlegen // Ohne Parameter Option help = new Option("help", "print this message"); // Optionsliste erstellen options = new Options(); options.addOption(minPWDAsciiCode ); options.addOption(help); ... .. . Optionen parsen: In der Dokumentation wird die Klasse „DefaultParser“ verwendet, in der aktuellen Version fehlt aber diese Klasse! Daher wird die Klasse „BasicParser“ eingesetzt. ... public static void main(String[] args) { // Create Help Output from the command options HelpFormatter formatter = new HelpFormatter(); // create the parser for the command line CommandLineParser parser = new BasicParser(); CommandLine cmdLine = null; try { // parse the command line arguments cmdLine = parser.parse(options, args); } catch (ParseException exp) { System.err.println("-- Error :: Wrong command :: Reason: " + exp.getMessage()); formatter.printHelp("PWD Check", options); System.exit(-1); } ... Parameter auswerten: ... if (cmdLine.hasOption("minAscii")) { minAscii= cmdLine.getOptionValue("minAscii"); } .. Hilfe ausgeben: ... // help Option if (cmdLine.hasOption("help")) { formatter.printHelp("PWD Check", options); System.exit(-1); } ... ===== Quellen ===== http://commons.apache.org/proper/commons-cli/index.html