简体   繁体   English

Java:如何从命令行中读取-input或--h之类的选项?

[英]Java: how to read options from command line like -input or --h?

Searched for a while now... I don't want to use a special parser, just build-in methods. 现在搜索了一段时间...我不想使用特殊的解析器,而只是使用内置方法。

The problem is I want to read options like -i=something in a simple way. 问题是我想以简单的方式读取-i=something类的选项。 Then - in the script - I can call these options like args[i] or so. 然后-在脚本中-我可以像args[i]这样调用这些选项。

Is there any way? 有什么办法吗? Thanks 谢谢

EDIT: Example 编辑:示例

Command Line: java scriptname -write="test" 命令行: java scriptname -write="test"

Script: System.out.println(args[write]); 脚本: System.out.println(args[write]);

Output: test 输出: test

If you want to you pass parameters as key-value pairs while invoking java program, you can do that using -D flag like this 如果要在调用Java程序时将参数作为键值对传递,则可以使用-D标志来实现,例如

java -Demail=test@gmail.com -DuserName="John Watson" MainProgam

If your value has spaces in it, enclose that in double quotes. 如果您的值中有空格,请将其括在双引号中。 Now you can access these values as system properties in your code like this 现在,您可以像这样在代码中将这些值作为系统属性来访问

String email = System.getProperty("email");
String name = System.getProperty("userName");

All the parameters passed after class name in java command are accessible in args[] of main method, you can access them only through indices not with key value pairs java命令的类名之后传递的所有参数都可以在main方法的args[]中访问,您只能通过索引访问它们,而不能使用键值对

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM