Parsowanie argumentów do programu wiersza poleceń Javy
A gdybym chciał to przeanalizować:
java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3
A wynik jaki chcę w moim programie to:
regular Java args[] of size=4
org.apache.commons.cli.Options[] of size=3
org.apache.commons.cli.Options[] #2 of size=1
Wolałbym użyć Apache Commons CLI , ale dokumentacja jest trochę niejasna co do sprawy, którą przedstawiam powyżej. W szczególności dokumentacja nie mówi ci, jak obsługiwać opcje trzeciego typu, które podaję poniżej:
1. options with a "-" char 2. options with a "--" char 3. options without any marker, or "bare args"
Chciałbym, aby Apache Commons CLI działało, ale nadal było w stanie przekazać zwykłe args do programu, jeśli te args nie mieć prefiks opcji. Może tak, ale dokumentacja nie mówi tak, gdy czytam...
8 answers
Możesz to zrobić ręcznie.
NB: może być lepiej użyć HashMap zamiast wewnętrznej klasy dla opcji.
/** convenient "-flag opt" combination */
private class Option {
String flag, opt;
public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }
}
static public void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<Option> optsList = new ArrayList<Option>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].length < 2)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
if (args[i].charAt(1) == '-') {
if (args[i].length < 3)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
// --opt
doubleOptsList.add(args[i].substring(2, args[i].length));
} else {
if (args.length-1 == i)
throw new IllegalArgumentException("Expected arg after: "+args[i]);
// -opt
optsList.add(new Option(args[i], args[i+1]));
i++;
}
break;
default:
// arg
argsList.add(args[i]);
break;
}
}
// etc
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-18 14:04:36
Użyj biblioteki Apache Commons CLI .getArgs (), aby uzyskać arg1, arg2, arg3 i arg4. Oto jakiś kod:
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Option.Builder;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
public static void main(String[] parameters)
{
CommandLine commandLine;
Option option_A = Option.builder("A")
.required(true)
.desc("The A option")
.longOpt("opt3")
.build();
Option option_r = Option.builder("r")
.required(true)
.desc("The r option")
.longOpt("opt1")
.build();
Option option_S = Option.builder("S")
.required(true)
.desc("The S option")
.longOpt("opt2")
.build();
Option option_test = Option.builder()
.required(true)
.desc("The test option")
.longOpt("test")
.build();
Options options = new Options();
CommandLineParser parser = new DefaultParser();
String[] testArgs =
{ "-r", "opt1", "-S", "opt2", "arg1", "arg2",
"arg3", "arg4", "--test", "-A", "opt3", };
options.addOption(option_A);
options.addOption(option_r);
options.addOption(option_S);
options.addOption(option_test);
try
{
commandLine = parser.parse(options, testArgs);
if (commandLine.hasOption("A"))
{
System.out.print("Option A is present. The value is: ");
System.out.println(commandLine.getOptionValue("A"));
}
if (commandLine.hasOption("r"))
{
System.out.print("Option r is present. The value is: ");
System.out.println(commandLine.getOptionValue("r"));
}
if (commandLine.hasOption("S"))
{
System.out.print("Option S is present. The value is: ");
System.out.println(commandLine.getOptionValue("S"));
}
if (commandLine.hasOption("test"))
{
System.out.println("Option test is present. This is a flag option.");
}
{
String[] remainder = commandLine.getArgs();
System.out.print("Remaining arguments: ");
for (String argument : remainder)
{
System.out.print(argument);
System.out.print(" ");
}
System.out.println();
}
}
catch (ParseException exception)
{
System.out.print("Parse error: ");
System.out.println(exception.getMessage());
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-18 21:45:04
Podoba mi się ten. Proste i masz więcej niż jeden parametr dla każdego argumentu:
final Map<String, List<String>> params = new HashMap<>();
List<String> options = null;
for (int i = 0; i < args.length; i++) {
final String a = args[i];
if (a.charAt(0) == '-') {
if (a.length() < 2) {
System.err.println("Error at argument " + a);
return;
}
options = new ArrayList<>();
params.put(a.substring(1), options);
}
else if (options != null) {
options.add(a);
}
else {
System.err.println("Illegal parameter usage");
return;
}
}
Na przykład:
-arg1 1 2 --arg2 3 4
System.out.print(params.get("arg1").get(0)); // 1
System.out.print(params.get("arg1").get(1)); // 2
System.out.print(params.get("-arg2").get(0)); // 3
System.out.print(params.get("-arg2").get(1)); // 4
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-15 07:11:21
You could use https://github.com/jankroken/commandline , Oto Jak to zrobić:
Aby ten przykład zadziałał, muszę założyć, co oznaczają argumenty - po prostu wybierając coś tutaj...
-r opt1 => replyAddress=opt1
-S opt2 arg1 arg2 arg3 arg4 => subjects=[opt2,arg1,arg2,arg3,arg4]
--test = test=true (default false)
-A opt3 => address=opt3
To może być ustawione w ten sposób:
public class MyProgramOptions {
private String replyAddress;
private String address;
private List<String> subjects;
private boolean test = false;
@ShortSwitch("r")
@LongSwitch("replyAddress") // if you also want a long variant. This can be skipped
@SingleArgument
public void setReplyAddress(String replyAddress) {
this.replyAddress = replyAddress;
}
@ShortSwitch("S")
@AllAvailableArguments
public void setSubjects(List<String> subjects) {
this.subjects = subjects;
}
@LongSwitch("test")
@Toggle(true)
public void setTest(boolean test) {
this.test = test;
}
@ShortSwitch("A")
@SingleArgument
public void setAddress(String address) {
this.address = address;
}
// getters...
}
A następnie w głównej metodzie możesz po prostu zrobić:
public final static void main(String[] args) {
try {
MyProgramOptions options = CommandLineParser.parse(MyProgramOptions.class, args, OptionStyle.SIMPLE);
// and then you can pass options to your application logic...
} catch
...
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-08 11:25:24
Oto rozwiązanie @ DwB zaktualizowane do zgodności z Commons CLI 1.3.1(zastąpione przestarzałymi komponentami OptionBuilder i GnuParser). Dokumentacja Apache używa przykładów, które w rzeczywistości mają nieoznaczone / nagie argumenty, ale je ignorują. Dzięki @ DwB za pokazanie jak to działa.
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.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public static void main(String[] parameters) {
CommandLine commandLine;
Option option_A = Option.builder("A").argName("opt3").hasArg().desc("The A option").build();
Option option_r = Option.builder("r").argName("opt1").hasArg().desc("The r option").build();
Option option_S = Option.builder("S").argName("opt2").hasArg().desc("The S option").build();
Option option_test = Option.builder().longOpt("test").desc("The test option").build();
Options options = new Options();
CommandLineParser parser = new DefaultParser();
options.addOption(option_A);
options.addOption(option_r);
options.addOption(option_S);
options.addOption(option_test);
String header = " [<arg1> [<arg2> [<arg3> ...\n Options, flags and arguments may be in any order";
String footer = "This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated methods replaced)";
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("CLIsample", header, options, footer, true);
String[] testArgs =
{ "-r", "opt1", "-S", "opt2", "arg1", "arg2",
"arg3", "arg4", "--test", "-A", "opt3", };
try
{
commandLine = parser.parse(options, testArgs);
if (commandLine.hasOption("A"))
{
System.out.print("Option A is present. The value is: ");
System.out.println(commandLine.getOptionValue("A"));
}
if (commandLine.hasOption("r"))
{
System.out.print("Option r is present. The value is: ");
System.out.println(commandLine.getOptionValue("r"));
}
if (commandLine.hasOption("S"))
{
System.out.print("Option S is present. The value is: ");
System.out.println(commandLine.getOptionValue("S"));
}
if (commandLine.hasOption("test"))
{
System.out.println("Option test is present. This is a flag option.");
}
{
String[] remainder = commandLine.getArgs();
System.out.print("Remaining arguments: ");
for (String argument : remainder)
{
System.out.print(argument);
System.out.print(" ");
}
System.out.println();
}
}
catch (ParseException exception)
{
System.out.print("Parse error: ");
System.out.println(exception.getMessage());
}
}
Wyjście:
usage: CLIsample [-A <opt3>] [-r <opt1>] [-S <opt2>] [--test]
[<arg1> [<arg2> [<arg3> ...
Options, flags and arguments may be in any order
-A <opt3> The A option
-r <opt1> The r option
-S <opt2> The S option
--test The test option
This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated
methods replaced)
Option A is present. The value is: opt3
Option r is present. The value is: opt1
Option S is present. The value is: opt2
Option test is present. This is a flag option.
Remaining arguments: arg1 arg2 arg3 arg4
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-14 20:26:02
Możesz użyć refcodes-console
artefaktu w refcodes-console na REFCODES.ORG:
Option<String> r = new StringOptionImpl( "-r", null, "opt1", "..." );
Option<String> s = new StringOptionImpl( "-S", null, "opt2", "..." );
Operand<String> arg1 = new StringOperandImpl( "arg1", "..." );
Operand<String> arg2 = new StringOperandImpl( "arg2", "..." );
Operand<String> arg3 = new StringOperandImpl( "arg3", "..." );
Operand<String> arg4 = new StringOperandImpl( "arg4", "..." );
Switch test = new SwitchImpl( null, "--test", "..." );
Option<String> a = new StringOptionImpl( "-A", null, "opt3", "..." );
Condition theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
test );
Utwórz swój Parser argumentów {[7] } z warunkiem roota:
ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
theArgsParser.setName( "MyProgramm" );
theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );
Powyżej definiujesz składnię, poniżej wywołujesz parser:
theArgsParser.printUsage();
theArgsParser.printSeparatorLn();
theArgsParser.printOptions();
theArgsParser.evalArgs( new String[] {
"-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444",
"--test", "-A", "AAAAA"
} );
W przypadku, gdy podałeś dobre opisy, theArgsParser.printUsage()
pokaże ci nawet ładny wydrukowany sposób użycia:
Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 --test
W powyższym przykładzie Wszystkie zdefiniowane argumenty muszą być przekazane przez użytkownika, w przeciwnym razie parser wykryje niewłaściwe użycie. Jeśli przełącznik
--test
ma być opcjonalny (lub jakikolwiek inny argument), PrzypisztheRoot
w następujący sposób:
TheRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl (test ) );
Wtedy twoja składnia wygląda następująco:
Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 [--test]
Pełny przykład twojego przypadku znajdziesz w StackOverFlowExamle . Możesz użyć warunków AND, OR, XOR i dowolnego rodzaju zagnieżdżania ... hope this pomaga.
Oceniaj przetworzone argumenty w następujący sposób:
r.getValue() );
lubif (test.getValue() == true) ...
:
LOGGER.info( "r :=" + r.getValue() );
LOGGER.info( "S :=" + s.getValue() );
LOGGER.info( "arg1 :=" + arg1.getValue() );
LOGGER.info( "arg2 :=" + arg2.getValue() );
LOGGER.info( "arg3 :=" + arg3.getValue() );
LOGGER.info( "arg4 :=" + arg4.getValue() );
LOGGER.info( "test :=" + test.getValue() + "" );
LOGGER.info( "A :=" + a.getValue() );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-06 10:33:45
Ok, dzięki Charles ' owi Goodwinowi za pomysł. Oto odpowiedź:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<String> optsList = new ArrayList<String>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i=0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].charAt(1) == '-') {
int len = 0;
String argstring = args[i].toString();
len = argstring.length();
System.out.println("Found double dash with command " +
argstring.substring(2, len) );
doubleOptsList.add(argstring.substring(2, len));
} else {
System.out.println("Found dash with command " +
args[i].charAt(1) + " and value " + args[i+1] );
i= i+1;
optsList.add(args[i]);
}
break;
default:
System.out.println("Add a default arg." );
argsList.add(args[i]);
break;
}
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-08 00:16:52
Prosty kod dla wiersza poleceń w Javie:
class CMDLineArgument
{
public static void main(String args[])
{
String name=args[0];
System.out.println(name);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-28 14:31:14