在shell工具中,有专门的getopt函数,使用方法如下所示:

while getopts "d:t:vh" opt; do
case "${opt}" in
"d")
DATE="${OPTARG}"
;;
"t")
ID="${OPTARG}"
ID2=`echo $ID | awk -F "_" '{print $2}'`
;;
"v")
printVersionInfo
exit 0
;;
"h")
printHelpInfo
exit 0
;;
esac
done

其中的”d:t:vh”就是可以接收的选项类型,其中-d和-t意味着可以其后面可以接收参数,而-v和-h后面因为没有:,表示不可以接收参数,只用于单独使用。于是使用这个shell脚本的方式就大概如下:

./example.sh –d “d的参数” –t “t的参数”
./example.sh –h
./example.sh –v

GetOpt在Java1.8的全称为:

com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt.GetOpt

Java程序员不能调用sun.*的相关包,以下是oracle给出的原因:

http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html

既然不能够直接调用,就拷贝过来,反正依赖也不多。

只需要少许改动,解除与ErrorMsg类的依赖,删除一个MissingOptException(同样改成IllegalArgumentException),就可以直接使用了,以下就是修改后的代码:

/*
* Copyright (c) 2007-2012, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: GetOpt.java,v 1.2.4.1 2005/08/31 11:46:04 pvedula Exp $
*/ import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator; /**
* GetOpt is a Java equivalent to the C getopt() library function
* discussed in man page getopt(3C). It provides command line
* parsing for Java applications. It supports the most rules of the
* command line standard (see man page intro(1)) including stacked
* options such as '-sxm' (which is equivalent to -s -x -m); it
* handles special '--' option that signifies the end of options.
* Additionally this implementation of getopt will check for
* mandatory arguments to options such as in the case of
* '-d <file>' it will throw a MissingOptArgException if the
* option argument '<file>' is not included on the commandline.
* getopt(3C) does not check for this.
*
* @author G Todd Miller
*/
public class GetOpt { public static final String ILLEGAL_CMDLINE_OPTION_ERR = "ILLEGAL_CMDLINE_OPTION_ERR"; public GetOpt(String[] args, String optString) {
theOptions = new ArrayList();
int currOptIndex = 0;
theCmdArgs = new ArrayList();
theOptionMatcher = new OptionMatcher(optString);
// fill in the options list
for (int i = 0; i < args.length; i++) {
String token = args[i];
int tokenLength = token.length();
if (token.equals("--")) { // end of opts
currOptIndex = i + 1; // set index of first operand
break; // end of options
} else if (token.startsWith("-") && tokenLength == 2) {
// simple option token such as '-s' found
theOptions.add(new Option(token.charAt(1)));
} else if (token.startsWith("-") && tokenLength > 2) {
// stacked options found, such as '-shm'
// iterate thru the tokens after the dash and
// add them to theOptions list
for (int j = 1; j < tokenLength; j++) {
theOptions.add(new Option(token.charAt(j)));
}
} else if (!token.startsWith("-")) {
// case 1- there are not options stored yet therefore
// this must be an command argument, not an option argument
if (theOptions.size() == 0) {
currOptIndex = i;
break; // stop processing options
} else {
// case 2-
// there are options stored, check to see if
// this arg belong to the last arg stored
int indexoflast = 0;
indexoflast = theOptions.size() - 1;
Option op = (Option) theOptions.get(indexoflast);
char opLetter = op.getArgLetter();
if (!op.hasArg() && theOptionMatcher.hasArg(opLetter)) {
op.setArg(token);
} else {
// case 3 -
// the last option stored does not take
// an argument, so again, this argument
// must be a command argument, not
// an option argument
currOptIndex = i;
break; // end of options
}
}
}// end option does not start with "-"
} // end for args loop // attach an iterator to list of options
theOptionsIterator = theOptions.listIterator(); // options are done, now fill out cmd arg list with remaining args
for (int i = currOptIndex; i < args.length; i++) {
String token = args[i];
theCmdArgs.add(token);
}
} /**
* debugging routine to print out all options collected
*/
public void printOptions() {
for (ListIterator it = theOptions.listIterator(); it.hasNext(); ) {
Option opt = (Option) it.next();
System.out.print("OPT =" + opt.getArgLetter());
String arg = opt.getArgument();
if (arg != null) {
System.out.print(" " + arg);
}
System.out.println();
}
} /**
* gets the next option found in the commandline. Distinguishes
* between two bad cases, one case is when an illegal option
* is found, and then other case is when an option takes an
* argument but no argument was found for that option.
* If the option found was not declared in the optString, then
* an IllegalArgumentException will be thrown (case 1).
* If the next option found has been declared to take an argument,
* and no such argument exists, then a MissingOptArgException
* is thrown (case 2).
*
* @return int - the next option found.
* @throws IllegalArgumentException, MissingOptArgException.
*/
public int getNextOption() throws IllegalArgumentException {
int retval = -1;
if (theOptionsIterator.hasNext()) {
theCurrentOption = (Option) theOptionsIterator.next();
char c = theCurrentOption.getArgLetter();
boolean shouldHaveArg = theOptionMatcher.hasArg(c);
String arg = theCurrentOption.getArgument();
if (!theOptionMatcher.match(c)) {
// ErrorMsg msg = new ErrorMsg(ErrorMsg.ILLEGAL_CMDLINE_OPTION_ERR,
// new Character(c));
throw (new IllegalArgumentException(String.format("%s : %s", ILLEGAL_CMDLINE_OPTION_ERR, new Character(c))));
} else if (shouldHaveArg && (arg == null)) {
throw (new IllegalArgumentException(String.format("%s : %s", ILLEGAL_CMDLINE_OPTION_ERR, new Character(c))));
}
retval = c;
}
return retval;
} /**
* gets the argument for the current parsed option. For example,
* in case of '-d <file>', if current option parsed is 'd' then
* getOptionArg() would return '<file>'.
*
* @return String - argument for current parsed option.
*/
public String getOptionArg() {
String retval = null;
String tmp = theCurrentOption.getArgument();
char c = theCurrentOption.getArgLetter();
if (theOptionMatcher.hasArg(c)) {
retval = tmp;
}
return retval;
} /**
* gets list of the commandline arguments. For example, in command
* such as 'cmd -s -d file file2 file3 file4' with the usage
* 'cmd [-s] [-d <file>] <file>...', getCmdArgs() would return
* the list {file2, file3, file4}.
*
* @return String[] - list of command arguments that may appear
* after options and option arguments.
* @params none
*/
public String[] getCmdArgs() {
String[] retval = new String[theCmdArgs.size()];
int i = 0;
for (ListIterator it = theCmdArgs.listIterator(); it.hasNext(); ) {
retval[i++] = (String) it.next();
}
return retval;
} private Option theCurrentOption = null;
private ListIterator theOptionsIterator;
private List theOptions = null;
private List theCmdArgs = null;
private OptionMatcher theOptionMatcher = null; ///////////////////////////////////////////////////////////
//
// Inner Classes
//
/////////////////////////////////////////////////////////// // inner class to model an option
class Option {
private char theArgLetter;
private String theArgument = null; public Option(char argLetter) {
theArgLetter = argLetter;
} public void setArg(String arg) {
theArgument = arg;
} public boolean hasArg() {
return (theArgument != null);
} public char getArgLetter() {
return theArgLetter;
} public String getArgument() {
return theArgument;
}
} // end class Option // inner class to query optString for a possible option match,
// and whether or not a given legal option takes an argument.
//
class OptionMatcher {
public OptionMatcher(String optString) {
theOptString = optString;
} public boolean match(char c) {
boolean retval = false;
if (theOptString.indexOf(c) != -1) {
retval = true;
}
return retval;
} public boolean hasArg(char c) {
boolean retval = false;
int index = theOptString.indexOf(c) + 1;
if (index == theOptString.length()) {
// reached end of theOptString
retval = false;
} else if (theOptString.charAt(index) == ':') {
retval = true;
}
return retval;
} private String theOptString = null;
} // end class OptionMatcher
}// end class GetOpt

我们先看GetOpt的构造函数,接收两个参数,第一个就是通过public static void main(String[] args)来指定的,也就是传过来的参数;第二个参数就更加重要了,这个是用来设置可接受选项类型的,这也是与shell中的getopt函数有着相同的含义。

下面就是一段关于getOpt函数的简单使用说明,对于每个选项,不用考虑其出现的顺序,这里也同样接收四种类型选项,其中d,t带具体的附加参数,而v,h没有附加参数,只作为帮助以及版本信息显示使用。

GetOpt getOpt = new GetOpt(args, "d:t:vh");
while ((c = getOpt.getNextOption()) != -1) {
System.out.println((char)c);
switch (c) {
case 'd':
dateString = getOpt.getOptionArg();
break;
case 't':
campaignId = getOpt.getOptionArg();
break;
case 'h' :
printHelpInfo();
break;
case 'v':
printVersionInfo();
break;
}
}

使用getNextOption()函数来逐个获取下一个选项,直到返回-1表示没有下一个参数可以处理。通过switch/case语句对每个选项的附加参数进行区分,并结合getOptionArg()返回该选项中的附件参数,并进行处理。

如果输入了不合法的参数字符,就会抛出以下的错误信息(表明a是未定义的参数字符):

java.lang.IllegalArgumentException: ILLEGAL_CMDLINE_OPTION_ERR : a
at.utils.GetOpt.getNextOption(GetOpt.java:151)

以上就是java中使用getOpt函数的总体介绍,这对于处理linux形式的参数有着非常好的支持,并且符合程序员的习惯。

Java中的GetOpt操作的更多相关文章

  1. JAVA中的时间操作

    java中的时间操作不外乎这四种情况: 1.获取当前时间 2.获取某个时间的某种格式 3.设置时间 4.时间的运算 好,下面就针对这四种情况,一个一个搞定. 一.获取当前时间 有两种方式可以获得,第一 ...

  2. java中的集合操作类(未完待续)

    申明: 实习生的肤浅理解,如发现有错误之处.还望大牛们多多指点 废话 事实上我写java的后台操作,我每次都会遇到一条语句:List<XXXXX> list = new ArrayList ...

  3. JAVA中通过Jedis操作Redis连接与插入简单库

    一.简述 JAVA中通过Jedis操作Redis连接与插入简单库 二.依赖 <!-- https://mvnrepository.com/artifact/redis.clients/jedis ...

  4. Java中的文件操作(一)RandomAccessFile

    今天,学到的是java中的文件操作. Java.IO.File Java中操作文件用到RandomAccessFile类,既可以读取文件内容,也可以向文件输出数据,但不同与普通输入/输出流的是Rand ...

  5. Java并发--Java中的CAS操作和实现原理

    版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/CringKong/article/deta ...

  6. Java中的字符串操作(比较String,StringBuiler和StringBuffer)

    一.前言 刚开始学习Java时,作为只会C语言的小白,就为其中的字符串操作而感到震撼.相比之下,C语言在字节数组中保存一个结尾的\0去表示字符串,想实现字符串拼接,还需要调用strcpy库函数或者自己 ...

  7. Java中的IO操作和缓冲区

    目录 Java中的IO操作和缓冲区 一.简述 二.IO流的介绍 什么是流 输入输出流的作用范围 三.Java中的字节流和字符流 字节流 字符流 二者的联系 1.InputStreamReader 2. ...

  8. java中的IO操作

    IO流是用来处理设备之间的数据传输,Java对数据的操作是通过流的方式进行,而操作流的对象都封装到java.io包中.根据操作数据的种类可以把IO流分为字节流(InputStream,OutputSt ...

  9. java和python细节总结和java中string 的+操作

    //JAVA中对arrayList的初始化,能够分配空间,不能之间让一个ArrayList赋值给另外一个ArrayList,这样是引用赋值,当一个改变时候,另外一个也改变 List<String ...

随机推荐

  1. Python面向对象的三大特征 --- 封装、继承、多态

    一.封装 1)封装:是面向对象的一大特点:将属性和方法封装在一个抽象类中.外界使用类创建对象,然后让对象调用内部方法.对象方法的细节都被封装在类的内部. class Person():   def _ ...

  2. 《Tomcat内核设计剖析》京东评论过百

    到京东看了下<Tomcat内核设计剖析>评论都一百多了,上个月也第二次印刷了,这里看下好评.中评和差评. 好评: 中评 对于中评,请看 为什么<写Tomcat内核设计剖析>,就 ...

  3. 【pandas】pandas.Series.str.split()---字符串分割

    原创博文,转载请注明出处! 本文代码的github地址       series中的元素均为字符串时,通过str.split可将字符串按指定的分隔符拆分成若干列的形式. 例子: 拆分以逗号为分隔符的字 ...

  4. iOS实现下拉放大的功能

    #import "HMViewController.h" ; @interface HMViewController () @property (nonatomic, weak) ...

  5. Android学习笔记之Activity详解

    1 理解Activity Activity就是一个包含应用程序界面的窗口,是Android四大组件之一.一个应用程序可以包含零个或多个Activity.一个Activity的生命周期是指从屏幕上显示那 ...

  6. HTTP请求报头及其处理

    ps:详细说明http://www.cnblogs.com/kkgreen/archive/2011/04/11/2012829.html

  7. BZOJ4150 AMPPZ2014 The Staging 【线段树】*

    BZOJ4150 AMPPZ2014 The Staging Description 在舞台上有n个枪手,第i个枪手瞄准了第p[i]个枪手,将于第u[i]秒开枪.一个枪手如果成功开枪, 那么被瞄准的枪 ...

  8. Codeforces 17E Palisection 【Manacher】

    Codeforces 17E Palisection E. Palisection In an English class Nick had nothing to do at all, and rem ...

  9. .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)

    长文预警!!! UWP 程序有 .NET Native 可以将程序集编译为本机代码,逆向的难度会大很多:而基于 .NET Framework 和 .NET Core 的程序却没有 .NET Nativ ...

  10. 理解 Roslyn 中的红绿树(Red-Green Trees)

    Roslyn 的 API 是非常易用的.即便如此复杂的 C# 语法,建立的复杂的 C# 语法树,还有其复杂的树遍历和修改过程,也都被其 API 包装得干净简洁. 而这背后是它的重要设计思路 —— 红绿 ...