栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

线上jar包获取resouce下的template/koukuandan.xls文件路径

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线上jar包获取resouce下的template/koukuandan.xls文件路径

package com.gbps.biz.qa.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

//获取临时文件路径
@Slf4j
@Component
public class DocUtil {

    //此路径是其余方法进行调用,且只须要加载一次
    private static String sourceTemplatePath;
    // 模板文件名称 位于 resource/template下面
    private static String[] ftlArray = {"koukuandan.xls"};
    // resources下模板文件夹名称
    private static String temPath = "template/";

    static {
        //静态方法调用一次 
        sourceTemplatePath = createFtlFileByFtlArray();
    }
    // 获取临时文件路径
    public String getSourceTemplatePath(){
        return sourceTemplatePath;
    }

    //获取临时文件模板路径
    public static String getRentalAgreementPath(){
        return sourceTemplatePath+ ftlArray[0];
    }

    private static String createFtlFileByFtlArray() {
        String path = "";
        for (int i = 0; i < ftlArray.length; i++) {
            path = createFtlFile(temPath, ftlArray[i]);
            if (null == path) {
                log.info("not copy success:" + ftlArray[i]);
            }
        }
        return path;
    }

    private static String createFtlFile(String ftlPath, String ftlName) {
        try {
            //获取当前项目所在的绝对路径
            String proFilePath = System.getProperty("user.dir");
            log.info("project run path:" + proFilePath);
            //获取模板下的路径 
            String newFilePath = proFilePath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + ftlPath;
            newFilePath = newFilePath.replace("/", File.separator);
            log.info("newFilePath:" + newFilePath);
            //检查项目运行时的src下的对应路径
            File newFile = new File(newFilePath + ftlName);
            if (newFile.isFile() && newFile.exists()) {
                return newFilePath;
            }
            //当项目打成jar包会运行下面的代码,而且复制一份到src路径下(具体结构看下面图片)
            InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ftlPath + ftlName);
            byte[] certData = IOUtils.toByteArray(certStream);
            FileUtils.writeByteArrayToFile(newFile, certData);
            return newFilePath;
        } catch (IOException e) {
            log.error("复制文件失败--> 异常信息:" + e);
        }
        return null;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036548.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号