java 根據html模板生成html文件


1.代碼部分

  1. import org.junit.Test;
  2. import org.junit.runner.RunWith;
  3. import org.springframework.boot.test.context.SpringBootTest;
  4. import org.springframework.test.context.junit4.SpringRunner;
  5.  
  6. import java.io.FileInputStream;
  7. import java.io.FileOutputStream;
  8.  
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. public class PdfApplicationTests {
  12.  
  13. @Test
  14. public void contextLoads() {
  15. String filePath = "D:\\WorkSpace\\IdeaProjects\\pdf\\src\\main\\resources\\templates\\index.html";
  16. String text = "哈哈";
  17. String disrPath = "D:\\WorkSpace\\IdeaProjects\\pdf\\src\\main\\resources\\templates";
  18. String fileName = "t";
  19. MakeHtml(filePath,text,disrPath,fileName);
  20. }
  21. /**
  22. * @Title: MakeHtml
  23. * @Description: 創建html
  24. * @param filePath 設定模板文件
  25. * @param text 添加的內容
  26. * @param disrPath 生成html的存放路徑
  27. * @param fileName 生成html名字
  28. * @return void 返回類型
  29. * @throws
  30. */
  31. public static void MakeHtml(String filePath,String text,String disrPath,String fileName ){
  32. try {
  33. String title = "<h2>"+text+"</h2>";
  34. System.out.print(filePath);
  35. String templateContent = "";
  36. FileInputStream fileinputstream = new FileInputStream(filePath);// 讀取模板文件
  37. int lenght = fileinputstream.available();
  38. byte bytes[] = new byte[lenght];
  39. fileinputstream.read(bytes);
  40. fileinputstream.close();
  41. templateContent = new String(bytes);
  42. System.out.print(templateContent);
  43. //把模板頁面上的 ###text### 替換成 title 里的內容
  44. templateContent = templateContent.replaceAll( "###text###", title);
  45. System.out.print(templateContent);
  46.  
  47. String fileame = fileName + ".html";
  48. fileame = disrPath+ "/" + fileame;// 生成的html文件保存路徑。
  49. FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件輸出流
  50. System.out.print( "文件輸出路徑:");
  51. System.out.print(fileame);
  52. byte tag_bytes[] = templateContent.getBytes();
  53. fileoutputstream.write(tag_bytes);
  54. fileoutputstream.close();
  55. } catch (Exception e) {
  56. System.out.print(e.toString());
  57. }
  58. }
  59. }
  60.  

2.模板頁

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>Title</title>
  6. </head>
  7. </head>
  8. <body>
  9. ###text###
  10. </body>
  11. </html>

3.生成的html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>Title</title>
  6. </head>
  7. </head>
  8. <body>
  9. <h2>哈哈</h2>
  10. </body>
  11. </html>

 


免責聲明!

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



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