SpringBoot項目打成jar包後無法讀取到resource下的文件

 

背景:最近工作研究整合ureport打印功能,需要在默認創建模板的時候保存一個基礎模板。需要讀取默認模板文件轉成字符串類型保存到數據庫。 

目錄結構如下

 

首先用第一種方式讀取配置文件:

     public String xmlToString(){
        SAXReader saxReader=new SAXReader();
        Document document;
        String xmlString="";
        try {
            InputStream in = ClassLoader.getSystemResourceAsStream("common-template.xml");
            document = saxReader.read(in);
            xmlString=document.asXML();//將xml內容轉化爲字符串
        } catch (Exception e) {
            e.printStackTrace();
            xmlString="";
        }
        return xmlString;
    }

在本地windows環境可以實現讀取,但是在linux上無法讀取。

第二種方式: 

   public String xmlToString() {
        String xmlString = "";
        try {
            StringBuffer content = new StringBuffer();
            InputStream stream = getClass().getClassLoader().getResourceAsStream("common-template.xml");
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            String s = "";
                while ((s = br.readLine()) != null) {
                    xmlString = xmlString + s;
            }
            br.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        log.info("common-template模板內容:"+xmlString);
        return xmlString;
    }

本地和linux上面都可以完成讀取。

總結:該項目是springboot工程是在Linux上面部署爲jar包,在Linux中無法直接訪問未經解壓的文件,所以就會找不到文件,

只能使用流的方式對靜態資源進行讀取.

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章