简体   繁体   中英

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. Then - in the script - I can call these options like args[i] or so.

Is there any way? Thanks

EDIT: Example

Command Line: java scriptname -write="test"

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

Output: 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 -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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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