前言
我們這邊有一個(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ù)