莫大人

如何制作可执行jar

1、如何制作可执行jar

1.1、引入依赖

<dependency>
    <groupId>commons-cli</groupId>
    <artifactId>commons-cli</artifactId>
    <version>1.3.1</version>
</dependency>

1.2、构建参数选项

1.3、解析参数

1.4、调用业务逻辑

如下:

package com.guo.test;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import org.apache.commons.cli.*;

public class TaskMain {

    public static void main(String[] args) {
        CommandLine commandLine = parseArguments(args);
        String src = commandLine.getOptionValue(CMD_SRC_FULL);
        String error = commandLine.getOptionValue(CMD_ERROR_FULL);
        Assert.notBlank(src, "-s 参数为空");
        Assert.notBlank(error, "-e 参数为空");
        System.out.println(JSONUtil.toJsonStr(new String[]{src, error}));
        try {
            TaskTest.cmd(src, error);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static CommandLine parseArguments(String[] arguments) {
        Options options = buildOptions();
        CommandLine commandLine = null;
        try {
            commandLine = new DefaultParser().parse(options, arguments);
        } catch (ParseException e) {
            e.printStackTrace();
            System.exit(1);
        }

        if (commandLine.hasOption(CMD_HELP_FULL)) {
            printHelp();
            System.exit(0);
        }
        return commandLine;
    }

    private static void printHelp() {
        Options options = buildOptions();
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar ${jar} [options]", options);
    }

    private static final String CMD_HELP_FULL = "help";
    private static final String CMD_HELP = "h";
    private static final String CMD_SRC_FULL = "src";
    private static final String CMD_SRC = "s";
    private static final String CMD_ERROR_FULL = "error";
    private static final String CMD_ERROR = "e";

    private static Options buildOptions() {
        Options options = new Options();
        options.addOption(Option.builder(CMD_SRC).argName("源数据").hasArg().longOpt(CMD_SRC_FULL).required(false).desc("src file patch, example:D:/src.txt").build());
        options.addOption(Option.builder(CMD_ERROR).argName("错误数据").hasArg().longOpt(CMD_ERROR_FULL).required(false).desc("error file patch, example:D:/error.txt").build());
        options.addOption(Option.builder(CMD_HELP).longOpt(CMD_HELP_FULL).desc("show command help").build());
        return options;
    }

}

1.5、生成MANIFEST.MF

1.5.1、打开IDEA设置页

File -> Project Structure -> Project Settings -> Artifacts

image

image

1.5.2、新增可执行jar

Add -> Jar -> from modules with dependencies

image

1.6、构建

image

image

1.7、执行测试

1.7.1、查看帮助

java -jar tms-tool.jar -h

image

1.7.2、执行命令

java -jar tms-tool.jar -s D:/test.txt -e D:/error.txt

posted on 2022-01-04 17:49  莫大人  阅读(168)  评论(0编辑  收藏  举报

导航