首页 > 编程语言 >利用SpringBoot的CommandLineRunner编写命令行jar程序

利用SpringBoot的CommandLineRunner编写命令行jar程序

时间:2024-04-25 18:57:22浏览次数:16  
标签:index CommandLineRunner SpringBoot ExcelProperty jar private value final String

1.项目pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/>
    </parent>

    <groupId>com.yang</groupId>
    <artifactId>excel-handler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>excel-handler</name>
    <description>excel-handler</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.2.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.2.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  1. 代码编写
package com.yang.excelhandler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@SpringBootApplication
public class ExcelHandlerApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ExcelHandlerApplication.class, args);
    }

    @Override
    public void run(String... args) {
        if (Objects.isNull(args) || args.length < 2) {
            throw new RuntimeException("请填写输入、输出文件路径!");
        }

        String inputFilePath = args[0];
        if (StringUtils.isBlank(inputFilePath)) {
            inputFilePath = "classpath:file.txt";
        }

        String outputFilePath = args[1];
        if (StringUtils.isBlank(outputFilePath)) {
            outputFilePath = "classpath:output.xlsx";
        }

        System.out.printf("-Input file path: %s.%n", inputFilePath);
        System.out.printf("--Output file path: %s.%n", outputFilePath);

        long start = System.currentTimeMillis();
        List<FortySixResult> list = MedicareCatalogTextFileParser.listBeanFromStaticFile(MedicareCatalogFileTypeEnum.CODE_MAPPING_46, inputFilePath);
        EasyExcel.write(new File(outputFilePath), FortySixResult.class).sheet("sheet_1").doWrite(list);
        long end = System.currentTimeMillis();
        System.err.printf("---处理完毕,耗时: %d ms.%n", end - start);
    }

}

@Getter
enum MedicareCatalogFileTypeEnum {

    CODE_MAPPING_46("46", "codeMappingInfo", "医保目录-编码对照信息", FortySixResult.class, "GB2312", "GB2312", "/Users/xiniuyiliao/Downloads/gs01_46.txt", (line) -> Arrays.asList(line.split("\t")));

    private final String code;

    private final String name;

    private final String description;

    public final Class<?> clazz;

    private final String sourceCharSet;

    private final String destCharSet;

    private final String filePath;

    private final Function<String, List<String>> separate;

    MedicareCatalogFileTypeEnum(String code, String name, String description, Class<?> clazz, String sourceCharSet, String destCharSet, String filePath, Function<String, List<String>> separate) {
        this.code = code;
        this.name = name;
        this.description = description;
        this.clazz = clazz;
        this.sourceCharSet = sourceCharSet;
        this.destCharSet = destCharSet;
        this.filePath = filePath;
        this.separate = separate;
    }

}

@Data
class FortySixResult {

    /**
     * 个人编号
     */
    @ExcelProperty(index = 0, value = "个人编号")
    private String aac001;

    /**
     * 个人帐户支付金额
     */
    @ExcelProperty(index = 1, value = "个人帐户支付金额")
    private String yka065;

    /**
     * 医疗费总额
     */
    @ExcelProperty(index = 2, value = "医疗费总额")
    private String yka055;

    /**
     * 全自费金额
     */
    @ExcelProperty(index = 3, value = "全自费金额")
    private String yka056;

    /**
     * 挂钩自付金额
     */
    @ExcelProperty(index = 4, value = "挂钩自付金额")
    private String yka057;

    /**
     * 符合范围金额
     */
    @ExcelProperty(index = 5, value = "符合范围金额")
    private String yka111;

    /**
     * 进入起付线金额
     */
    @ExcelProperty(index = 6, value = "进入起付线金额")
    private String yka058;

    /**
     * 基本医疗统筹支付金额
     */
    @ExcelProperty(index = 7, value = "基本医疗统筹支付金额")
    private String yka248;

    /**
     * 大额医疗支付金额
     */
    @ExcelProperty(index = 8, value = "大额医疗支付金额")
    private String yka062;

    /**
     * 公务员补助报销金额
     */
    @ExcelProperty(index = 9, value = "公务员补助报销金额")
    private String yke030;

    /**
     * 个人账户支付后余额
     */
    @ExcelProperty(index = 10, value = "个人账户支付后余额")
    private String ykc177;

    /**
     * 清算分中心
     */
    @ExcelProperty(index = 11, value = "清算分中心")
    private String ykb037;

    /**
     * 清算类别
     */
    @ExcelProperty(index = 12, value = "清算类别")
    private String yka316;

    /**
     * 清算方式
     */
    @ExcelProperty(index = 13, value = "清算方式")
    private String yka054;

    /**
     * 清算期号
     */
    @ExcelProperty(index = 14, value = "清算期号")
    private String yae366;

    /**
     * 医疗人员类别
     */
    @ExcelProperty(index = 15, value = "医疗人员类别")
    private String akc021;

    /**
     * 就诊结算方式
     */
    @ExcelProperty(index = 16, value = "就诊结算方式")
    private String ykc121;

    /**
     * 居保人员类别
     */
    @ExcelProperty(index = 17, value = "居保人员类别")
    private String ykc280;

    /**
     * 居保人员身份
     */
    @ExcelProperty(index = 18, value = "居保人员身份")
    private String ykc281;

    /**
     * 经办时间
     */
    @ExcelProperty(index = 19, value = "经办时间")
    private String aae036;

    /**
     * 门诊住院流水号
     */
    @ExcelProperty(index = 20, value = "门诊住院流水号")
    private String akc190;

    /**
     * 姓名
     */
    @ExcelProperty(index = 21, value = "姓名")
    private String aac003;

    /**
     * 结算编号
     */
    @ExcelProperty(index = 22, value = "结算编号")
    private String yka103;

    /**
     * 执行社会保险办法
     */
    @ExcelProperty(index = 23, value = "执行社会保险办法")
    private String ykb065;

    /**
     * 支付类别
     */
    @ExcelProperty(index = 24, value = "支付类别")
    private String aka130;

    /**
     * 行政区划
     */
    @ExcelProperty(index = 25, value = "行政区划")
    private String yab003;

    /**
     * 经办人编码
     */
    @ExcelProperty(index = 26, value = "经办人编码")
    private String aae011;

    /**
     * 经办人姓名
     */
    @ExcelProperty(index = 27, value = "经办人姓名")
    private String ykc141;

    /**
     * 医疗救助
     */
    @ExcelProperty(index = 28, value = "医疗救助")
    private String yka469;

    /**
     * 卫计补偿
     */
    @ExcelProperty(index = 29, value = "卫计补偿")
    private String yka471;

    /**
     * 优抚补偿
     */
    @ExcelProperty(index = 30, value = "优抚补偿")
    private String ake183;

    /**
     * 其它基金
     */
    @ExcelProperty(index = 31, value = "其它基金")
    private String ake173;

    /**
     * 参保分中心
     */
    @ExcelProperty(index = 32, value = "参保分中心")
    private String yab139;

}

final class MedicareCatalogTextFileParser {

    /**
     * 根据字段长度切分原始字符,字段值集合
     *
     * @param line
     * @return
     */
    private static List<String> cutLine(final String line, final Function<String, List<String>> separate) {
        return separate.apply(line);
    }

    /**
     * 利用字段值集合,构建对象
     *
     * @param filedValueList
     * @param clazz
     * @param <T>
     * @return
     */
    private static <T> T buildBeanFromFiledValueList(final List<String> filedValueList, final Class<T> clazz) {
        Field[] declaredFieldArr = clazz.getDeclaredFields();
        int min = Math.min(filedValueList.size(), declaredFieldArr.length);
        Field.setAccessible(declaredFieldArr, true);
        T t;
        try {
            t = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        for (int i = 0; i < min; i++) {
            Field field = declaredFieldArr[i];
            try {
                field.set(t, StringUtils.trim(filedValueList.get(i)));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return t;
    }

    /**
     * 从文本行提取单个对象
     *
     * @param line
     * @param clazz
     * @param sourceCharSet
     * @param destCharSet
     * @param separate
     * @param <T>
     * @return
     */
    private static <T> T extractSingleBeanFromTextLine(final String line, final Class<T> clazz, final String sourceCharSet, final String destCharSet, final Function<String, List<String>> separate) {
        List<String> fieldValueList = cutLine(StringUtils.trim(line), separate).stream().map(it -> {
            try {
                return new String(it.getBytes(sourceCharSet), destCharSet);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return it;
        }).collect(Collectors.toList());
        return buildBeanFromFiledValueList(fieldValueList, clazz);
    }

    /**
     * 从输入流中提取对象集合
     *
     * @param inputStream
     * @param clazz
     * @param sourceCharSet
     * @param destCharSet
     * @param separate
     * @param <T>
     * @return
     * @throws IOException
     */
    @SneakyThrows
    public static <T> List<T> parseFromInputStream(final InputStream inputStream, final Class<T> clazz, final String sourceCharSet, final String destCharSet, final Function<String, List<String>> separate) {
        List<T> instanceList = new ArrayList<>();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, sourceCharSet))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (StringUtils.isBlank(line)) {
                    continue;
                }
                instanceList.add(MedicareCatalogTextFileParser.extractSingleBeanFromTextLine(line, clazz, sourceCharSet, destCharSet, separate));
            }
        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        }
        return instanceList;
    }

    /**
     * 从静态文件中提取对象集合
     *
     * @param typeEnum
     * @param <T>
     * @return
     * @throws Exception
     */
    @SneakyThrows
    @Deprecated
    public static <T> List<T> listBeanFromStaticFile(final MedicareCatalogFileTypeEnum typeEnum, final String inputFilePath) {
        return (List<T>) parseFromInputStream(Files.newInputStream(Paths.get(inputFilePath)), typeEnum.getClazz(), typeEnum.getSourceCharSet(), typeEnum.getDestCharSet(), typeEnum.getSeparate());
    }

}
  1. 运行jar包
java -jar excel-handler.jar "./gs01_46.txt" "./2.xlsx"

标签:index,CommandLineRunner,SpringBoot,ExcelProperty,jar,private,value,final,String
From: https://www.cnblogs.com/JaxYoun/p/18158354

相关文章

  • springboot中使用spring-javaformat-maven-plugin格式化代码插件
    在springboot项目中,想通过使用插件来统一项目中的代码,我这里选用的是spring-javaformat-maven-plugin。maven项目中,使用步骤如下:一、导入插件依赖pom.xml中添加<build><plugins><!--格式化代码插件--><plugin><groupId>i......
  • springboot+mybatisplus+dynicDatasource 从数据库表中查询数据源 动态添加
    1、pom依赖<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version><relativePath/><!--lookuppa......
  • springboot mybatis-plus dynamic-datasource实现
    基础架构是springboot+mybatis-plus实现动态数据源步骤步骤1:pom文件<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version>......
  • SpringBoot项目添加2FA双因素身份认证
    什么是2FA(双因素身份验证)?双因素身份验证(2FA)是一种安全系统,要求用户提供两种不同的身份验证方式才能访问某个系统或服务。国内普遍做短信验证码这种的用的比较少,不过在国外的网站中使用双因素身份验证的还是很多的。用户通过使用验证器扫描二维码,就能在app上获取登录的动态口令,......
  • SpringBoot项目实现日志打印SQL明细(包括SQL语句和参数)几种方式
    前言我们在开发项目的时候,都会连接数据库。有时候遇到问题需要根据我们编写的SQL进行分析,但如果不进行一些开发或者配置的话,这些SQL是不会打印到控制台的,它们默认是隐藏的。下面给大家介绍几种常用的方法。第一种、代码形式Mybatis框架是Java程序员最常用的数据库映射框架,MyBa......
  • 9.prometheus监控--监控springboot2.x(Java)
    一、环境部署yumsearchjava|grepjdkyuminstall-yjava-11-openjdk-devel二、监控java应用(tomcat/jar)JMXexporter负责收集Java虚拟机信息---没举例,等以后再做测试进入到tomcat安装目录,vimPROMETHEUS_JMX_EXPORTER_OPTS="-javaagent:../prometheus-exporter......
  • springboot的netty代码实操
    参考:https://www.cnblogs.com/mc-74120/p/13622008.htmlpom文件<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId></dependency>启动类@EnableFeignClients@EnableDiscoveryClient@EnableSchedu......
  • k8s Java 项目替换 jar 中的 class 文件
    背景紧急需求,客户需要立马上线docker包体积过大,远程不稳定,文件发不过去单点修改,风险低步骤1.获取pod所在宿主机podonhostkubectl-n$namespancegetpods-owide|grep$podname|grepRunning2.获取pod的容器cidkubectl-n$namespancedescribepo$podn......
  • 服务器部署jar包执行命令编写
    服务器部署jar包执行命令编写新建deploy.sh文件,并编写内容SERVER_NAME=demo-server-8.2.0.15.jar#服务jar包名称#根据服务名称查询对应的pidpid=$(ps-ef|grep$SERVER_NAME|grep-vgrep|awk'{print$2}');#判断进程是否存在,存在则杀死if[-n"$pid"];thenkill......
  • springboot 结合jackson数据脱敏
     在返回字段时有时需要对电话,地址等字段进行脱敏处理1.定义枚举脱敏类使用函数编程,绑定函数操作publicenumDataMaskEnum{/***名称脱敏*/USERNAME(s->s.replaceAll("(\\S)\\S(\\S*)","$1*$2")),/***手机号脱敏*/......