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


在我們的D盤下有這樣一個html模板,現在我們要做的就是解析news.template文件,從數據庫中提取數據將數據添加到指定的模板位置上

 1 <head>
 2     <title>{title}</title>
 3 </head>
 4 <body>
 5     <table align="center" width="95" border="1">
 6         <tr>
 7             <td width="10%"><b>標簽:</b></td>
 8             <td>{title}</td>
 9         </tr>
10         <tr>
11             <td width="10%"><b>作者:</b></td>
12             <td>{author}</td>
13         </tr>
14         <tr>
15             <td width="10%"><b>時間:</b></td>
16             <td>{createTime}</td>
17         </tr>
18         <tr>
19             <td width="10%"><b>內容:</b></td>
20             <td>{content}</td>
21         </tr>
22     </table>
23 </body>
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     }
String readFile(String path) throws IOException

 

編寫方法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);
toHtml() throws SQLException, IOException

 

最終結果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM