在我们的D盘下有这样一个html模板,现在我们要做的就是解析news.template文件,从数据库中提取数据将数据添加到指定的模板位置上

  news.template

 

接下来使用IO流的InputStream将该文件读取到内存中

 1 //读取HTML模板文件new.template
 2     public String readFile(String path) throws IOException{
 3 InputStream is=null;
 4         String result="";
 5         try {
 6             @SuppressWarnings("unused")
 7             int data=0;
 8             byte[] by =new byte[1024];
 9             is = new FileInputStream(path);
10             while((data=is.read(by))!=-1){
11                 //result+=(char)data;
12                 //result=new String(data);
13                 result=new String(by,0,by.length);
14             }
15         } catch (FileNotFoundException e) {
16             System.out.println("未找到new.template文件!");
17             e.printStackTrace();
18         }
19         finally{
20             System.out.println("创建成功!");
21             is.close();
22         }
23         //return result.toString();
24         return result;
25     }

 

编写方法toHTml()   替换模板文件,为每条新闻创建一个HTML文件来显示其信息

 1 //读取数据库表,获取新闻列表信息(在此不做讲解)
 2 List<News> list = dao.allInfo();
 3 //编写方法  将从数据库中读取到的数据替换掉news.template文件中的占位符"{}"
 4 String template= fileio.readFile("D:\\news.template");
 5         
 6         //替换模板文件,为每条新闻创建一个HTML文件来显示其信息
 7         for (int i = 0; i < list.size(); i++) {
 8             //获取一条新闻信息
 9             News news=list.get(i);
10             //使用该条新闻信息替换对应占位符
11             String replacetr = new String();
12             replacetr=template;
13             //replace(char oldChar, char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的
14             replacetr=replacetr.replace("{title}",news.getTitle());
15             replacetr=replacetr.replace("{author}",news.getAuthor());
16             replacetr=replacetr.replace("{createTime}",news.getDatetime().toString());
17             replacetr=replacetr.replace("{content}",news.getContent());
18             //为该条新闻生成HTML文件
19             String filepath="D:\\dbtohtml\\new"+i+".html";
20             
21             fileio.writeFile(filepath,replacetr);

 

最终结果如下

 

更多推荐

java中使用String的replace方法替换html模板保存文件