java 根据html模板生成html文件

时间:2022-10-15 20:56:27

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>