springboot项目在Linux环境下,打出的jar包找不到资源文件的问题总结

今天的开发中遇到的一个问题:

我在resources目录下的templates下建了一个xml文件。

在config类中想读取这个文件, 我使用了如下的代码:

File file = ResourceUtils.getFile("classpath:templates/importEXCEL.xml");

这种代码在windows下是没有问题的,但是一旦打包到了linux环境下,linux系统在jar包路径上多加了!符号,导致程序按这种路径找文件找不到。

改成下面这种写法就可以了:

ClassPathResource classPathResource = new ClassPathResource("templates/importEXCEL.xml");

 

附上xml文件和代码:


import com.techen.tap.exception.BusinessException;
import com.techen.tap.utils.I18nUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @param paraMap
 * @Modify: EXCEL导入模板操作类
 * @author: lihao
 * @date: 2021/5/12 17:33
 * @return ResponseResult<Object>
 */
@Configuration
@Component
public class EXCELConfig {

    //    @Value("${excel.xmlPath}")
//    static String xmlPath;
    final static String EXAMPLE = "example";
    final static String DEFAULT = "default";

    Document document;

    public EXCELConfig() throws FileNotFoundException, DocumentException {
        ClassPathResource classPathResource = new ClassPathResource("templates/importEXCEL.xml");
//        File file = ResourceUtils.getFile("classpath:templates/importEXCEL.xml");
//        File file = ResourceUtils.getFile(xmlPath);
//        InputStream in = new FileInputStream(file);
        InputStream in = null;
        try {
            in = classPathResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        SAXReader reader = new SAXReader();
        document = reader.read(in);
    }

    /**
     * @param paraMap
     * @return ResponseResult<Object>
     * @Modify: 获取模板配置中的所有模板名称
     * @author: lihao
     * @date: 2021/5/15 13:55
     */
    public StringBuffer getAllExcelModelName() {
        StringBuffer result = new StringBuffer();
        // 获取xml文档根节点
        Element root = document.getRootElement();
        List<Element> listElement = root.elements();
        for (int i = 0; i < listElement.size(); i++) {
            String elementName = listElement.get(i).getName();
            result.append(elementName);
        }
        return result;
    }

    /**
     * @param paraMap
     * @return ResponseResult<Object>
     * @Modify: 按模版名称获取模版的excel文件
     * @author: lihao
     * @date: 2021/5/15 14:12
     */
    public byte[] getExcelModelByName(String modelName) throws IOException {
        // 获取xml文档根节点
        Element root = document.getRootElement();
        Element element = root.element(modelName);
        if (element == null) {
            return null;
        }
        //构造excel文件
        HSSFWorkbook excel = new HSSFWorkbook();
        HSSFSheet sheet0 = excel.createSheet(element.getName());
        HSSFRow rowNameExcel = sheet0.createRow(0);
        HSSFRow rowDataExcel = sheet0.createRow(1);
        List<Element> colList = element.elements();
        for (int i = 0; i < colList.size(); i++) {
            String data = colList.get(i).getData().toString();
            // 标头
            HSSFCell cellExcel = rowNameExcel.createCell(i);
            cellExcel.setCellValue(data);
            // 示例内容
            HSSFCell cellExample = rowDataExcel.createCell(i);
            Attribute attribute = colList.get(i).attribute(EXAMPLE);
            if (attribute != null) {
                cellExample.setCellValue(attribute.getValue());
            }
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        excel.write(bos);
        byte[] brray = bos.toByteArray();
        return brray;
    }

    /**
     * @param paraMap
     * @return ResponseResult<Object>
     * @Modify: excel转换为map
     * 将要导入的excel表格信息转换为map格式
     * @author: lihao
     * @date: 2021/5/22 11:47
     */
    public List<Map> exacleToMap(MultipartFile file, String modelName) {
        HSSFWorkbook excel = null;
        HSSFSheet sheet = null;
        HSSFRow row = null;
        List<Map> resultMap = new ArrayList<>();

        //构造excel文件
        try {
            excel = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
        } catch (IOException e) {
            throw new BusinessException(I18nUtil.getMessageDefault("file.InvalidFormat", "文件格式错误,请重试"));
        }

        // 获取指定名称的节点
        Element root = document.getRootElement();
        Element elementModel = root.element(modelName);
        List<Element> elements = elementModel.elements();

        if (excel != null) {
            for (int i = 0; i < excel.getNumberOfSheets(); i++) {
                sheet = excel.getSheetAt(i);
                // 从索引为1的行开始获取
                for (int r = 1; r < sheet.getPhysicalNumberOfRows(); r++) {
                    row = sheet.getRow(r);
                    for (int c = 0; c < row.getPhysicalNumberOfCells(); c++) {
                        Map map = new HashMap();
                        String key = elements.get(c).getName();
                        map.put(key, row.getCell(c));
                        resultMap.add(map);
                    }
                }
            }
        }
        System.out.print(resultMap.toString());
        return resultMap;
    }
}

xml文件代码:

<root>
    <ConsAccount>
        <cons_name default="1" example="张三">用户名称</cons_name>
        <cons_addr default="1" example="省市区">用户地址</cons_addr>
        <identity_card default="1" example="XXX">身份证号</identity_card>
        <cons_tel default="1" example="XXX">电话号码</cons_tel>
        <contact_name default="1" example="张三">联系人</contact_name>
        <postal_code default="1" example="05321">邮政编码</postal_code>
        <cons_email default="1" example="xxx@qq.com">电子邮件</cons_email>
        <inuse_num default="1" example="3">使用人口</inuse_num>
        <living_area default="1" example="108">居住面积</living_area>
        <msg_mobile default="1" example="XXX">短信提醒号码</msg_mobile>
    </ConsAccount>
    <Meter>
        <install_addr default="1" example="xxx">安装地址</install_addr>
        <comm_module_addr default="1" example="xxx">模块地址</comm_module_addr>
        <asset_no default="1" example="xxx">资产号</asset_no>
        <run_status_code default="01" example="xxx">运行状态</run_status_code>
        <flag_total default="0" example="xxx">总分类型</flag_total>
        <flag_download default="1" example="xxx">档案上云状态</flag_download>
        <R_val default="1" example="78">R值</R_val>
        <thermal_adapt default="1" example="34℃~67℃">温度自适应性</thermal_adapt>
    </Meter>
</root>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值