java argumentparser_Java命令行解析库 Argparse4j详解

  • Post author:
  • Post category:java


fff6c98081bf8904098fb5e1bd59ff4b.gif

argparse4j 是 Python argparse 命令行解析器的 Java 语言移植版。

它的主要特性:

1.支持位置参数和可选参数.

2.变量数量的参数.

3.生成格式化行换行帮助消息.

4.考虑到东亚宽度自动换行时模棱两可的字符.

5.Sub-commands,git添加.

6.可定制的选项前缀字符,例如.“+ f”和“/ h”.

7.打印帮助信息的默认值.

8.选择从给定的值的集合.

9.从选项字符串类型转换.

10.可以直接赋值到用户定义的类中使用注释.

11.组参数,这样它将打印在更可读的方式帮助信息.

示例代码:

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.ByteChannel;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import net.sourceforge.argparse4j.ArgumentParsers;

import net.sourceforge.argparse4j.inf.ArgumentParser;

import net.sourceforge.argparse4j.inf.ArgumentParserException;

import net.sourceforge.argparse4j.inf.Namespace;

public class Checksum {

public static void main(String[] args) {

ArgumentParser parser = ArgumentParsers.newArgumentParser(“Checksum”)

.defaultHelp(true)

.description(“Calculate checksum of given files.”);

parser.addArgument(“-t”, “–type”)

.choices(“SHA-256”, “SHA-512”, “SHA1”).setDefault(“SHA-256”)

.help(“Specify hash function to use”);

parser.addArgument(“file”).nargs(“*”)

.help(“File to calculate checksum”);

Namespace ns = null;

try {

ns = parser.parseArgs(args);

} catch (ArgumentParserException e) {

parser.handleError(e);

System.exit(1);

}

MessageDigest digest = null;

try {

digest = MessageDigest.getInstance(ns.getString(“type”));

} catch (NoSuchAlgorithmException e) {

System.err.printf(“Could not get instance of algorithm %s: %s”,

ns.getString(“type”), e.getMessage());

System.exit(1);

}

for (String name : ns.

getList(“file”)) {

Path path = Paths.get(name);

try (ByteChannel channel = Files.newByteChannel(path,

StandardOpenOption.READ);) {

ByteBuffer buffer = ByteBuffer.allocate(4096);

while (channel.read(buffer) > 0) {

buffer.flip();

digest.update(buffer);

buffer.clear();

}

} catch (IOException e) {

System.err

.printf(“%s: failed to read data: %s”, e.getMessage());

continue;

}

byte md[] = digest.digest();

StringBuffer sb = new StringBuffer();

for (int i = 0, len = md.length; i < len; ++i) {

String x = Integer.toHexString(0xff & md[i]);

if (x.length() == 1) {

sb.append(“0”);

}

sb.append(x);

}

System.out.printf(“%s  %s\n”, sb.toString(), name);

}

}

}

fff6c98081bf8904098fb5e1bd59ff4b.gif

转载请注明来源网站:www.itxm.cn谢谢!

分享到:



版权声明:本文为weixin_33642697原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。