---
title: "使用Java编写基于命令行的程序"
author: "witcheryne"
date: "2013-04-14T17:32:07Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-04-14T17:45:39Z"
id: 1847187
url: "https://witcheryne.iteye.com/blog/1847187"
---

平时工作中，会用Java编写基于命令行的小工具。本片将介绍如何使用Java编写基于命令行的程序。

 

## 命令行程序需要包含的内容

- 命令行参数解析
- 程序以及参数说明
- 程序功能的实现(这个根据自己情况而定)

## Java中如何处理命令行参数

最直接的处理命令行的方法:

```
public class Cli {
	public static void main (String [] args)
	{
		for(String arg : args ) {
			System.out.println(arg);
		}
	}
}
```

运行：

 

```
m-lv:cli lvjian$ javac Cli.java
m-lv:cli lvjian$ java Cli
m-lv:cli lvjian$ java Cli -file filename
-file
filename
```

 

## 复杂一点的命令处理

下面这段代码摘自我的Java2ObjC Tools工具:

### Ant中的运行脚本

```
     <target name="rk2" depends="compile">
         <java fork="true" classname="tools.restkit.RKTools" classpathref="classpath">
             <classpath path="${classes.dir}"/>
             <arg value="-o"/>
             <arg value="/Users/lvjian/macspace/changji/changji/src/models"/>
             <arg value="-v"/>
             <arg value="2"/>
             <arg value="-excludes" />
             <arg value="TaskCounts,TaskCycle,TaskLog,TaskRouter,FormatGroup,Project,Device,DevicePort"/>
         </java>
     </target>
```

### 程序代码段

```
	public static void main(String[] args) throws ClassNotFoundException {
		ClassPathXmlApplicationContext ctx = 
			new ClassPathXmlApplicationContext("/tools/spring/restkit.xml");
		RKTools tools = (RKTools)ctx.getBean("rktools");
		
		if(args[0].equals("-o")) {
			String output = args[1];
			log.info("output path:" + output);
			tools.setTargetSrc(output);
		}
		
		if(args[2].equals("-v")) {
			String version = args[3];
			log.info("version:" + version);
			tools.setVersion(version);
		}
		
		if(args[4].equals("-excludes")) {
			String excludes = args[5];
			if(excludes != null) {
				String[] arr = excludes.split(",");
				tools.setExcludes(arr);
			}
		}
		
		tools.generate();
	}
```

如果每个参数都这么解析，那太痛苦了。况且这里用了大量代码只做了解析工作，并且还没有做提供命令行参数说明文档。一般使用 [Apache Common Cli](http://commons.apache.org/proper/commons-cli/) 包解决。

 

## 一个完成的例子

### 使用Apache Common Cli 改造之前的 Cli 代码

（[代码可以在附件找到](http://dl.iteye.com/topics/download/0441958e-c549-3049-9d7f-02d79962d111)）

```
import org.apache.commons.cli.*;

public class Cli {

	static Options opts = new Options();
	
	static {
        // 配置两个参数
        // -h --help 帮助文档
        // -f --file file参数
		opts.addOption("h", "help", false, "The command help");
		opts.addOption("f", "file", false, 
				"Input your file name.");
	}
   
    /**
     * 提供程序的帮助文档
     */
    static void printHelp(Options opts) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("The Cli app. Show how to use Apache common cli.", opts);
	}

	public static void main (String [] args) throws ParseException {
        // 解析参数
		CommandLineParser parser = new PosixParser();
		CommandLine cl = parser.parse(opts, args);
        
        if(cl.hasOption("h")) {
            printHelp(opts);
            return;
		}

        String filename = cl.getOptionValue("file");
        System.out.println(filename);
	}
}
```

### 运行

```
m-lv:cli lvjian$ java -jar cli.jar -h
usage: The Cli app. Show how to use Apache common cli.
 -f,--file <arg>   Input your file name.
 -h,--help         The command help
m-lv:cli lvjian$ java -jar cli.jar -f fileparameter
fileparameter
m-lv:cli lvjian$ java -jar cli.jar -file fileparameter
fileparameter
```

### 附件代码说明

1. 使用Apache Ant编译
2. ant默认指令为: ant jar

## 真实的使用案例:

mas-message

[https://github.com/lvjian700/mas-message](https://github.com/lvjian700/mas-message)

提供给C++客户端使用，调用北京电视的内部短信接口。

可供学习的内容:

- Apache Common Cli 包的使用
- C 通过命令行调用 Jar包
- Java中使用System.exit()方法传递退出值