Java中的GetOpt操作
在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操作的更多相关文章
- JAVA中的时间操作
java中的时间操作不外乎这四种情况: 1.获取当前时间 2.获取某个时间的某种格式 3.设置时间 4.时间的运算 好,下面就针对这四种情况,一个一个搞定. 一.获取当前时间 有两种方式可以获得,第一 ...
- java中的集合操作类(未完待续)
申明: 实习生的肤浅理解,如发现有错误之处.还望大牛们多多指点 废话 事实上我写java的后台操作,我每次都会遇到一条语句:List<XXXXX> list = new ArrayList ...
- JAVA中通过Jedis操作Redis连接与插入简单库
一.简述 JAVA中通过Jedis操作Redis连接与插入简单库 二.依赖 <!-- https://mvnrepository.com/artifact/redis.clients/jedis ...
- Java中的文件操作(一)RandomAccessFile
今天,学到的是java中的文件操作. Java.IO.File Java中操作文件用到RandomAccessFile类,既可以读取文件内容,也可以向文件输出数据,但不同与普通输入/输出流的是Rand ...
- Java并发--Java中的CAS操作和实现原理
版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/CringKong/article/deta ...
- Java中的字符串操作(比较String,StringBuiler和StringBuffer)
一.前言 刚开始学习Java时,作为只会C语言的小白,就为其中的字符串操作而感到震撼.相比之下,C语言在字节数组中保存一个结尾的\0去表示字符串,想实现字符串拼接,还需要调用strcpy库函数或者自己 ...
- Java中的IO操作和缓冲区
目录 Java中的IO操作和缓冲区 一.简述 二.IO流的介绍 什么是流 输入输出流的作用范围 三.Java中的字节流和字符流 字节流 字符流 二者的联系 1.InputStreamReader 2. ...
- java中的IO操作
IO流是用来处理设备之间的数据传输,Java对数据的操作是通过流的方式进行,而操作流的对象都封装到java.io包中.根据操作数据的种类可以把IO流分为字节流(InputStream,OutputSt ...
- java和python细节总结和java中string 的+操作
//JAVA中对arrayList的初始化,能够分配空间,不能之间让一个ArrayList赋值给另外一个ArrayList,这样是引用赋值,当一个改变时候,另外一个也改变 List<String ...
随机推荐
- 【LeetCode 88_数组】Merge Sorted Array
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { ; ; ; &&a ...
- vue.js 源代码学习笔记 ----- $watcher
/* @flow */ import { queueWatcher } from './scheduler' import Dep, { pushTarget, popTarget } from '. ...
- TF随笔-7
求平均值的函数 reduce_mean axis为1表示求行 axis为0表示求列 >>> xxx=tf.constant([[1., 10.],[3.,30.]])>> ...
- 从JDK源码角度看Byte
Java的Byte类主要的作用就是对基本类型byte进行封装,提供了一些处理byte类型的方法,比如byte到String类型的转换方法或String类型到byte类型的转换方法,当然也包含与其他类型 ...
- linux下升级svn版本到1.8
CentOS6.5默认yum安装的svn版本为1.6,有时候遇到比较高级的应用就可能不够使用,这时候就需要升级一下svn的版本,可以升级到的版本为1.8 ====== 完美的分割线 ====== 1. ...
- Python 中的 if __name__ == '__main__'
__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ .这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行. 先来个小栗子: 先创建一个 ...
- Spring之基本关键策略
目的 为了简化Java开发. 策略 基于POJO(普通Java类)的轻量级和最小侵入性编程: 通过依赖注入(DI)和面向接口实现松耦合: 基于切面和惯例进行声明式编程: 通过切面和模板减少样板式代码. ...
- 真机调试watch的一系列bug
真机调试watch的一系列bug 系列一 WatchKit 2.0 app's bundle ID com.jiaoshi.memoKB is not prefixed by the parent a ...
- js之放大镜效果
HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...
- 程序设计入门-C语言基础知识-翁恺-期中测试
一.试题 程序设计入门—C 语言期中测评 试题下载地址: http://nos.netease.com/edu-lesson-pdfsrc/217E194E46A6595A3F554380337490 ...