需求:
本地有一個生成sql腳本的檔案,預留了很多類似 {{xxx}} 需要替換的地方 ,
該需求是 需要前端傳入回應的值 替換掉 模板中預留的需要被替換的位置
最后 通過Post請求回傳給前端一個供其下載一個.sql腳本檔案
實作步驟
1、首先,考慮到打包后的路徑問題
想到了SpringBoot工程下的Resource目錄下
所以 我們需要的模板檔案跟提供給前端下載的檔案就放在 Resource 目錄下的static檔案夾里
//于是我就寫了一個方法用于提取該路徑
//用到了Spring ApplicationHome類的方法
public String getSavePath() {
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
return applicationHome.getDir().getParentFile()
.getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\";
}
2、檔案復制替換
這里我試過用FileReader和FileWriter方法
但是由于 這兩個方法是不可以設定檔案encode編碼的(或者是可以 我不會 = =!)
所以,因為需要替換的地方不多,我就想到了一部分用字串拼接,一部分用BufferedWriter寫

由于業務需要 寫了兩個其他方法
生成隨機一位字串
private String MkRandomNum() {
Random random = new Random();
String randomNum = "";
for (int i = 0; i < 9; i++) {
randomNum += random.nextInt(10);
}
return randomNum;
}
日期格式的轉換
private String toFormatDate(String modifyTime) {
Date format2 = null;
try {
format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(modifyTime);
} catch (ParseException e) {
throw new RuntimeException(e);
}
String shortDate = new SimpleDateFormat("yyyyMMddHHmmss").format(format2);
return shortDate;
}
讀取原模板檔案為字串并設定字符編碼
public String readToString(String fileName) {
String encoding = "UTF-8";
File file = new File(fileName);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(filecontent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return null;
}
}
3、使用HttpServletResponse回傳給前端
@Override
public void export(HttpServletResponse response) throws IOException {
String realPath = getSavePath()+"demo2.sql";
String fileName = ("model.sql");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
FileInputStream fis = new FileInputStream(realPath);
//5、創建緩沖區
int len = 0;
byte[] bytes = new byte[1024];
//6、創建輸出流
ServletOutputStream sot = response.getOutputStream();
//7、寫出檔案
while ((len = fis.read(bytes)) != -1) {
sot.write(bytes, 0, len);
sot.flush();
}
//8、關閉流
sot.close();
fis.close();
}
4、部分結果展示

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544676.html
標籤:Java
上一篇:使用 Docker 部署 Spring Boot 專案
下一篇:idea 無法加載主類
