springboot jar啟動 讀取jar包中相對路徑文件報錯


jar包啟動后讀取相對路徑文件報異常:
Caused by: java.io.FileNotFoundException: class path resource [***.***] cannot be resolved to absolute 
.***.jar/BOOT-INF/classes!/***.**

采用流的方式讀取即可解決

// /template/template.html是resource下面的文件
String template=readfile("/template/template.html");
//file 相對路徑
 public  String readfile(String file){
        InputStream stream = this.getClass().getResourceAsStream(file);
        StringBuffer sb = new StringBuffer() ;
        BufferedReader br = null ;
        try {
            br = new BufferedReader(new InputStreamReader(stream,"UTF-8")) ;
            String s=null ;
            while((s=br.readLine()) !=null){
                sb.append(s) ;
            }
            br.close();
        } catch (FileNotFoundException e) {
            log.error("FileNotFoundException:"+e);
        } catch (IOException e) {
            log.error("IOException :"+e);
        }finally {
            if(br !=null){
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("close br error:"+e);
                }
            }
        }
        return sb.toString();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM