Die folgende Klasse bietet einen simplen Command-Line Parser.
Alle Argumente die mit einem Minus anfangen werden als relevante Argumente erfasst und können nachfolgende Argumente welche kein voranführendes Minus haben als Wert nutzen.
Beispiele:
- Code: [Alles auswählen] [Auf-/Zuklappen]
-a -b -c foo Speichert {-a:true; -b:true, -c: foo}
-a foo Speichert {-a: foo}
a Speichert nichts
Der Code:
- Code: [Alles auswählen] [Auf-/Zuklappen]
/*
* 2012(c) By Marc Sven Kleinboehl aka Hroudtwolf
* All rights reserved.
*/
package utilities;
import java.util.HashMap;
public class CommandLineParser {
private HashMap<String, String> commandLineArgument;
/*
* CTor.
* @param String[] saArguments An array of command line arguments.
*/
public CommandLineParser (String[] saArguments) {
int nI = 0;
this.commandLineArgument = new HashMap<String, String> ();
while (saArguments.length > nI) {
if (saArguments[nI].startsWith("-") || saArguments[nI].startsWith("/")) {
if (saArguments.length > nI + 1 && ! (saArguments[nI + 1].startsWith("-") || saArguments[nI + 1].startsWith("/"))) {
this.commandLineArgument.put (saArguments[nI], saArguments[nI + 1]);
}else{
this.commandLineArgument.put (saArguments[nI], "");
}
}
nI++;
}
return;
}
/*
* Checks whether a specific argument exists.
* @param String sArgument The key of the argument.
* @return boolean TRUE if the argument exists.
*/
public boolean hasArgument (String sArgument) {
return this.commandLineArgument.containsKey(sArgument);
}
/*
* Retrieves the value of a specific argument.
* @param String sArgument The key of the argument.
* @return String The value of the argument on success. Otherwise an empty string.
*/
public String getArgumentValue (String sArgument) {
if (! this.hasArgument (sArgument)) {
return "";
}
return this.commandLineArgument.get(sArgument);
}
/*
* Retrieves the value of a specific argument.
* @param String sArgument The key of the argument.
* @param String sDefault The optional default value. It will returned if the argument doesn't exists.
* @return String The value of the argument on success. Otherwise an empty string.
*/
public String getArgumentValue (String sArgument, String sDefault) {
if (! this.hasArgument (sArgument)) {
return sDefault;
}
return this.commandLineArgument.get(sArgument);
}
}
LG
Wolf

