There is an HTML template under our D drive, and now all we have to do is parse the News.template file, extract the data from the database, add the data to the specified template location
12<title>{title}</title>34<body>5<table align="Center"Width=" the"Border="1">6<tr>7<TD width="10%"><b> label:</b></td>8<td>{title}</td>9</tr>Ten<tr> One<TD width="10%"><b> author:</b></td> A<td>{author}</td> -</tr> -<tr> the<TD width="10%"><b> Time:</b></td> -<td>{createTime}</td> -</tr> -<tr> +<TD width="10%"><b> content:</b></td> -<td>{content}</td> +</tr> A</table> at</body>
news.template
Next use the IO stream's inputstream to read the file into memory
1 //reading HTML template files New.template2 Publicstring ReadFile (String path) throws ioexception{3InputStream is=NULL;4String result="";5 Try {6@SuppressWarnings ("Unused")7 intData=0;8 byte[] by =New byte[1024x768];9 is=NewFileInputStream (path);Ten while((data= is. Read (by))!=-1){ One //result+= (char) data; A //result=new String (data); -result=NewString (By,0, by.length); - } the}Catch(FileNotFoundException e) { -System. out. println ("new.template file not found! "); - e.printstacktrace (); - } + finally{ -System. out. println ("Create success! "); + is. Close (); A } at //return result.tostring (); - returnresult; -}
string ReadFile (String path) throws IOException
Write Method tohtml () to replace the template file, create an HTML file for each news to display its information
1 //read the database table, get the News list information (do not explain here)2list<news> list =dao.allinfo ();3 //Write method replaces the placeholder "{}" in the News.template file with the data read from the database4String template= fileio.readfile ("D:\\news.template");5 6 //Replace the template file and create an HTML file for each news to display its information7 for(inti = 0; I < list.size (); i++) {8 //get a piece of news information9News news=List.get (i);Ten //replace the corresponding placeholder with this news message OneString REPLACETR =NewString (); AReplacetr=template; - //replace (char OldChar, char Newchar) returns a new string that is obtained by replacing all OldChar that appear in this string with Newchar . -Replacetr=replacetr.replace ("{title}", News.gettitle ()); theReplacetr=replacetr.replace ("{Author}", News.getauthor ()); -Replacetr=replacetr.replace ("{createtime}", News.getdatetime (). toString ()); -Replacetr=replacetr.replace ("{content}", News.getcontent ()); - //generate an HTML file for this piece of news +String filepath= "D:\\dbtohtml\\new" +i+ ". html"; - +Fileio.writefile (FILEPATH,REPLACETR);
toHtml () throws SQLException, IOException
The final result is as follows
Replace HTML template with the Replace method of string in Java save file