一、java代码
设置好数据源map
Mapmap=new HashMap<>(); map.put("knowledgeName",tBasKnowledgebase.getKnowledgeName()); map.put("htmlContent",tBasKnowledgebase.getHtmlContent()); map.put("publishDate",new java.text.SimpleDateFormat("yyyy-MM-dd").format(tBasKnowledgebase.getPublishDate())); CreateHtmlUtils.MakeHtml(rpath,map,htmlPath,tBasKnowledgebase.getKnowledgeId());
工具类方法
/** * @Title: MakeHtml * @Description: 创建html * @param filePath 设定模板文件 * @param map 需要显示图片的路径 * @param disrPath 生成html的存放路径 * @param fileName 生成html名字 * @return void 返回类型 * @throws */ public static void MakeHtml(String filePath, Mapmap, String disrPath, String fileName ){ try { System.out.print(filePath); String templateContent = ""; // 读取模板文件,模板文件,是工程中的一个html页面,里面有一些需要替换的字段 FileInputStream fileinputstream = new FileInputStream(filePath); int lenght = fileinputstream.available(); byte bytes[] = new byte[lenght]; fileinputstream.read(bytes); fileinputstream.close(); templateContent = new String(bytes, "utf-8"); System.out.print(templateContent); // 替换掉模板中的一些字段,填充数据渲染页面 for (Map.Entry entry : map.entrySet()) { String key=entry.getKey(); String value=entry.getValue(); templateContent = templateContent.replaceAll("###"+key+"###", value); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } System.out.print(templateContent); String fileame = fileName + ".html"; // 生成的html文件保存路径,html文件全路径,选择服务器上工程目录下以外的路径,持久化存储到硬盘,这样发布新版本原来的静态文件不会丢失 fileame = disrPath+"/" + fileame; // 根据文件全路径创建file对象 File file=new File(fileame); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } if(!file.exists()){ file.createNewFile(); } FileOutputStream fileOutputStream=new FileOutputStream(file); OutputStreamWriter oStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8"); // 将替换完数据的模板页面形成的文件流持久化到硬盘 oStreamWriter.append(templateContent); oStreamWriter.close(); } catch (Exception e) { System.out.print(e.toString()); } }
工程中的模板HTML文件:
效果: