java 生成html  网上的大部分资料都是 用 ##title## 这样的模板替换,但是 这种方式不能满足 假如 有一个list 的数据 要循环的 构建 tr  这种方式 因此 采用 流的形式 将 html 模板 以字符串 形式读出来 在 构建 html 内容 在写入 即可

 

代码:

 

public class HTMLGenerator {

     public static boolean jspToHtmlFile(String filePath,String htmlFile,List<SolrBean> list){
         
               String    title="";
             String    content ="";
             String    id ="";
             String    context="";
             String    html = "";
         
             String str = "";
             try {
                 FileInputStream is = new FileInputStream(filePath);
                 BufferedReader br = new BufferedReader(new InputStreamReader(is));
                 String tempStr = "";
                 while((tempStr = br.readLine()) != null){
                        str = str + tempStr;
             }
                 br.close();
                 is.close();
             } catch (IOException e) {
                   e.printStackTrace();
                   
                   return false;
             }
             for(int i=0;i<list.size();i++){
                 title =list.get(i).getTitle();
                 content = list.get(i).getContent();
                 id = list.get(i).getId();
              
                 html  += "<div>" +list.get(i).getTitle()+ "<div><br>"  
                       +  "<div>" +list.get(i).getContent()+ "<div><br>" 
                       + "<div>" +list.get(i).getId()+ "<div><br>";
              }   
             
             try {
                 context = html+"<!--search_end-->";
                 System.out.println("context:["+context+"]");
                 str = str.replace("<!--search_end-->", context);
                 
                 System.out.println("str:["+str+"]");
                 File file = new File(htmlFile);
                 //BufferedWriter writer = new BufferedWriter(new FileWriter(file));
                 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"UTF-8")));
                 out.write(str);
                 out.close(); 
             
             }catch (IOException e) {
                 e.printStackTrace();
                 return false;
             }
           
             return true;
     }
         public static void main(String[] args) {
         String url = "D:\\Workspaces\\base.html";
         String savePath = "d:\\" + 11 + ".html";
         
         //jspToHtmlFile(url, savePath);
     }
 }