解決springboot讀取jar包中文件的問(wèn)題

前言

我們這邊有一個(gè)需求如下:

  • 有一個(gè)模板文件,有占位符,在添加產(chǎn)品的時(shí)候,將占位符中內(nèi)容替換成相應(yīng)的產(chǎn)品信息并生成文件。
    在項(xiàng)目中使用的是springboot,在本地讀取文件因?yàn)椴皇且詊ar包的方式訪問(wèn),所以可以讀取到文件內(nèi)容,而在服務(wù)器上以jar的形式讀取,所以讀取的文件內(nèi)容為空。
    先貼上代碼
private static String readScript(String filePath){
    File file=new File(filePath);
    Long fileLength=file.length();
    byte[] fileContext=new byte[fileLength.intValue()];
    try {
        FileInputStream in=new FileInputStream(filePath);
        in.read(fileContext);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new String(fileContext);
}

這樣讀到文件路徑為:

file:/home/build/admin/rampage-admin-web-0.1.0-SNAPSHOT-exec.jar!/BOOT-INF/classes!/templates/script.ftl

但是文件內(nèi)容為空,并沒有報(bào)錯(cuò)異常信息。后來(lái)百度后改為

private static String readScript(File file){
    Long fileLength=file.length();
    byte[] fileContext=new byte[fileLength.intValue()];
    try {
        FileInputStream in=new FileInputStream(file);
        in.read(fileContext);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new String(fileContext);
}

參數(shù)File 的值如下:

InputStream stream = getClass().getClassLoader().getResourceAsStream("templates/script.ftl");
File targetFile = new File("script.ftl");
FileUtils.copyInputStreamToFile(stream, targetFile);

此處targetFile即為參數(shù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容