Java命令行解析庫 Argparse4j
argparse4j 是 Python argparse 命令行解析器的 Java 語言移植版。
它的主要特性:
- Supported positional arguments and optional arguments.
- Variable number of arguments.
- Generates well formatted line-wrapped help message.
- Takes into account East Asian Width ambiguous characters when line-wrap.
- Sub-commands like, git add.
- Customizable option prefix characters, e.g. '+f' and '/h'.
- Print default values in help message.
- Choice from given collection of values.
- Type conversion from option strings.
- Can directly assign values into user defined classes using annotation.
- Group arguments so that it will be printed in help message in more readable way.
示例代碼:
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); } }
}
</string></pre>
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!