freemarker将文件读写到HTML中

freemarker将文件读写到HTML中


1、设计思路

(1)写freemarker模板方法

(2)写測试文件方法

(3)新建ftl文件

(4)在指定的路径下。新建目录


2、写freemarker模板方法

/**
       * 输出文件到指定的路径下
       * @Title:printFile
       * @Description:
       * @param:@param name
       * @param:@param root
       * @param:@param outputFile
       * @return: void
       * @throws
       */
      public void printFile(String name,Map<String,Object> root,String outputFile)
      {
    	  FileWriter out = null;
    	  try 
    	  {
    		  //写入到指定的文件路径
    		  out = new FileWriter(new File("D:\MyEclipse\Maven\ftl\" + outputFile));
    		  Template temp = this.getTemplate(name);
    		  try 
    		  {
    			  temp.process(root, out);
		  } 
    		  catch (TemplateException e) 
    		  {
    			  e.printStackTrace();
		  }
	  } 
    	  catch (IOException e) 
    	  {
    		  e.printStackTrace();
	  }
    	  finally
    	  {
    		  if(out != null)
		  try 
    		   {
			//关闭文件流
			out.close();
		    } 
    		    catch (IOException e) 
    		    {
			e.printStackTrace();
		    }
    	  }
      }

3、写測试文件方法

/**
	 * 
	 * @Title:testFreemarkerFile
	 * @Description:
	 * @param:
	 * @return: void
	 * @throws
	 */
	@Test
	public void testFreemarkerFile()
	{
		//创建数据模型
		Map<String,Object> root = new HashMap<String,Object>();
		//为数据模型加入值
		root.put("username", "张三");
		root.put("age", "22");
		root.put("sex", "男");
		//将数据模型和模板中的数据输出到控制台
		ft.printFile("user.ftl", root,"user.html");
	}

4、新建ftl文件

姓名:${username}
年龄:${age}
性别:${sex}

5、新建目录

D:MyEclipseMavenftl


6、生成结果

(1)生成user.html



(2)控制台生成的结果

姓名:张三
年龄:22
性别:男




原文地址:https://www.cnblogs.com/zsychanpin/p/7008325.html