Java Main参数解析(Args4j)
最近实现一个工具,Main函数会有很多参数,而且参数类型不同,为了统一解析,网上找到三方工具类Args4j,轻松搞定。
代码实例如下:
定义解析类:
import java.io.File import org.kohsuke.args4j.Option
import org.slf4j.LoggerFactory /**
* 数据库报表生成命令行参数定义
*
* @author BarryWang create at 2018/6/23 20:21
* @version 0.0.1
*/
class ArgOptions {
val logger= LoggerFactory.getLogger(classOf[ArgOptions]) /**
* 对象名及查询SQL脚本对,中间用英文分号":"隔开
*/
val query = new scala.collection.mutable.ListBuffer[(String, String, String)];
@Option(name = "-q",
aliases = Array("-query"),
metaVar = "<db>:<objectName>:<sql>",
usage = "对象名及查询SQL脚本对,中间用英文分号“:”隔开, 例如database:objectName:sql。(String)")
def setProperty(property: String): Unit = {
var arr = property.split(":")
arr.length match {
case 3 => query.+=((arr(0), arr(1), arr(2)))
case _ => logger.info("-query 传入参数格式错误, 正确格式: <db>:<objectName>:<sql>")
}
} /**
* JXLS Excel模板文件绝对路径
*/
@Option(name = "-t",
aliases = Array("-template"),
metaVar = "<template file>",
usage = "JXLS Excel模板文件绝对路径, 请参考:http://jxls.sourceforge.net/reference/simple_exporter.html。(File)" )
var template: File = null /**
* Scala脚本文件
*/
@Option(name = "-s",
aliases = Array("-script"),
metaVar = "<scala script file path>",
usage = "Scala脚本文件, 请参考:http://ammonite.io/#ScalaScripts。(String)")
var script: String = null /**
* 输出Excel文件
*/
@Option(name = "-o",
aliases = Array("-output"),
/* required = true,handler = classOf[StringArrayOptionHandler],*/
metaVar = "<output excel file>",
usage = "输出Excel文件绝对路径。(File)")
var output: String = null /**
* 输出Excel文件
*/
@Option(name = "-m",
aliases = Array("-mailto"),
metaVar = "<email>",
usage = "生成报表发送邮箱,多个使用英文分号“;”分割。(String)")
var email: String = null /**
* 邮件主题
*/
@Option(name = "-sub",
aliases = Array("-subject"),
metaVar = "<subject>",
usage = "邮件主题。(String)")
var subject: String = null
}
引用解析类如下:
import java.io.File
import java.util.Date import com.today.dbreport.action.impl.{GenReportByScriptAction, GenReportBySqlAction, GenReportByTemplateBySqlAction}
import com.today.dbreport.dto.GenReportParam
import com.today.dbreport.utils.EmailUtil
import com.today.service.commons.util.DateTools
import org.kohsuke.args4j.CmdLineParser
import org.slf4j.LoggerFactory import scala.collection.JavaConverters._ /**
* 生成报表入口
*
* @author BarryWang create at 2018/6/1 11:02
* @version 0.0.1
*/
object Main {
val logger= LoggerFactory.getLogger(Main.getClass) def main(args: Array[String]): Unit = {
val options = new ArgOptions
val parser = new CmdLineParser(options)
// print usage
parser.printUsage(System.out)
parser.parseArgument(args.toList.asJava) //输出文件或发送邮件必填一个
if(options.output == null && options.email == null){
println("请传入参数-output 或 -mailto其中之一")
return
} //生成报表地址
var utf8Output = ""
if (options.output != null) {
utf8Output = new String(options.output.getBytes("UTF-8"), "UTF-8")
} else {//本地临时文件
val currentTime = DateTools.format(new Date(), "yyyyMMddHHmmssSSS")
val outDir = s"${System.getProperty("user.dir")}${File.separator}output"
var outputDir = new File(outDir)
if(!outputDir.exists()){
outputDir.mkdirs()
}
utf8Output = s"${outDir}${File.separator}${currentTime}.xlsx"
}
//带有Scala脚本
if (options.script != null) {
var templateOptional: Option[File] = None
if (options.template != null) {
templateOptional = Some(options.template)
}
val scriptOptional = Some(options.script)
var mailtoOptional: Option[String] = None
if (options.email != null) {
mailtoOptional = Some(options.email)
}
val genReportParam = new GenReportParam(options.query, utf8Output, templateOptional, scriptOptional, mailtoOptional)
//sql + script + jxls template
//script + jxls tempalte
new GenReportByScriptAction(genReportParam).execute
} else {//无Scala脚本
var templateOptional: Option[File] = None
if (options.template != null){
templateOptional = Some(options.template)
}
var scriptOptional : Option[String] = None
if(options.script != null){
scriptOptional = Some(options.script)
} var mailtoOptional: Option[String] = None
if (options.email != null){
mailtoOptional = Some(options.email)
} val genReportParam = new GenReportParam(options.query, utf8Output, templateOptional, scriptOptional, mailtoOptional)
if (options.template != null) { //sql* + jxls template
new GenReportByTemplateBySqlAction(genReportParam).execute
} else { //no template + sql
new GenReportBySqlAction(genReportParam).execute
}
} println(s"报表生成成功${utf8Output}!")
//发送邮件
if (options.email != null) {
var subject = "报表工具生成报表"
if(options.subject != null){
subject = options.subject
}
EmailUtil.sendEmail(options.email.trim, subject, "生成报表请参考附件", utf8Output)
println("邮件发送成功,请邮件附件下载相关报表!")
//邮件发送成功, 删除本地临时文件
if (options.output == null) {
new File(utf8Output).deleteOnExit()
}
}
logger.info(s"报表生成成功${utf8Output}")
}
}
运行main函数会展示如下提示:
-f (-from) <from> : 邮件发送者。(String)
-m (-mailto) <email> : 生成报表发送邮箱,多个使用英文分号“;”分割。(String)
-o (-output) <output excel file> : 输出Excel文件绝对路径。(File)
-q (-query) <db>:<objectName>:<sql> : 对象名及查询SQL脚本对,中间用英文分号“:”隔开,
例如database:objectName:sql。(String)
-s (-script) <scala script file path> : Scala脚本文件, 请参考:http://ammonite.io/#Scal
aScripts。(String)
-sub (-subject) <subject> : 邮件主题。(String)
-t (-template) <template file> : JXLS Excel模板文件绝对路径, 请参考:http://jxls.sou
rceforge.net/reference/simple_exporter.
html。(File)
请传入参数-output 或 -mailto其中之一
是不是就看起来很直观了!
Java Main参数解析(Args4j)的更多相关文章
- 打印Java main参数
public class Main { public static void main(String args[]){ System.out.println("打印main方法中的输入参数, ...
- java笔试之参数解析(正则匹配)
在命令行输入如下命令: xcopy /s c:\ d:\, 各个参数如下: 参数1:命令字xcopy 参数2:字符串/s 参数3:字符串c:\ 参数4: 字符串d:\ 请编写一个参数解析程序,实现将命 ...
- java 获取url及url参数解析
java 获取url及url参数解析 一.url编码:URLEncoder.encode(userName); 二.url解码: URLDecoder.decode(userName);
- Java注解全面解析(转)
1.基本语法 注解定义看起来很像接口的定义.事实上,与其他任何接口一样,注解也将会编译成class文件. @Target(ElementType.Method) @Retention(Retentio ...
- Java 面试知识点解析(二)——高并发编程篇
前言: 在遨游了一番 Java Web 的世界之后,发现了自己的一些缺失,所以就着一篇深度好文:知名互联网公司校招 Java 开发岗面试知识点解析 ,来好好的对 Java 知识点进行复习和学习一番,大 ...
- Java 面试知识点解析(三)——JVM篇
前言: 在遨游了一番 Java Web 的世界之后,发现了自己的一些缺失,所以就着一篇深度好文:知名互联网公司校招 Java 开发岗面试知识点解析 ,来好好的对 Java 知识点进行复习和学习一番,大 ...
- Java 面试知识点解析(四)——版本特性篇
前言: 在遨游了一番 Java Web 的世界之后,发现了自己的一些缺失,所以就着一篇深度好文:知名互联网公司校招 Java 开发岗面试知识点解析 ,来好好的对 Java 知识点进行复习和学习一番,大 ...
- 【转载】Java类加载原理解析
Java类加载原理解析 原文出处:http://www.blogjava.net/zhuxing/archive/2008/08/08/220841.html 1 基本信息 摘要: 每个j ...
- SpringBoot系列教程web篇之如何自定义参数解析器
title: 190831-SpringBoot系列教程web篇之如何自定义参数解析器 banner: /spring-blog/imgs/190831/logo.jpg tags: 请求参数 cat ...
随机推荐
- 【数据结构】B-Tree, B+Tree, B*树介绍
[摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是浮云,目前Mysql的MyISAM和InnoDB都支持B-Tree索引,InnoDB还支持B+Tree索引,Memory ...
- RCTF 2018线上赛 writeup
苦逼的RCTF,只进行了两天,刚好第二天是5.20,出去xxx了,没法打比赛,难受.比赛结束了,还不准继续提交flag进行正确校验了,更难受. 下面是本次ctf解题思路流程 后面我解出的题会陆续更新上 ...
- 10. 搭配redis做文章缓存
redis是一个使用较多的内存键值数据库,这儿的键是字符串类型的标识符,而值可以是字符串.散列.列表.集合和有序集合,也正是因为redis提供了较丰富的值的类型,能够满足不同的使用要求,而且redis ...
- Github管理自己的代码-远程篇
一.名词解释 Git Git是一个开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. Git 是 Linus Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版 ...
- Reactor和Proactor模式
在高性能的I/O设计中,有两个比较著名的模式Reactor和Proactor模式,其中Reactor模式用于同步I/O,而Proactor运用于异步I/O操作.同步和异步 同步和异步是针对应用程序和内 ...
- maven+springmvc的配置
1. 首先创建1个mavenweb项目 如果没有的话最好是去官网下载一个最新版本的eclipse 里面什么都有 maven/gradle 啥的 2. 选择路径 没啥影响 就是一个路径 默认就行 ...
- laravel 中路由的快速设置(只需一个控制器名就ok) 不用具体到方法
routes/web.php 设置路由 Route::group(['middleware' => ['\iqiyi\Http\Middleware\VerifyCsrfToken::class ...
- Java IO--字符流--InputStreamReader 和 OutputStreamWriter
今天继续学习字符流的子类!!!! 先来熟悉一下适配器设计模式:(手写的,,嘿嘿) 因为据说InputStreamReader 和OutputStreamWriter采用了适配器模式(现在我还没能理解, ...
- java jackson 忽略不存在的属性字段 和 按照属性名转json
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibi ...
- Universal-Image-Loader源码解解析---display过程 + 获取bitmap过程
Universal-Image-Loader在github上的地址:https://github.com/nostra13/Android-Universal-Image-Loader 它的基本使用请 ...