
正文
java中使用String的replace方法替换html模板保存文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
在我们的D盘下有这样一个html模板,现在我们要做的就是解析news.template文件,从数据库中提取数据将数据添加到指定的模板位置上

<head>
<title>{title}</title>
</head>
<body>
<table align="center" width="" border="">
<tr>
<td width="10%"><b>标签:</b></td>
<td>{title}</td>
</tr>
<tr>
<td width="10%"><b>作者:</b></td>
<td>{author}</td>
</tr>
<tr>
<td width="10%"><b>时间:</b></td>
<td>{createTime}</td>
</tr>
<tr>
<td width="10%"><b>内容:</b></td>
<td>{content}</td>
</tr>
</table>
</body>
news.template
接下来使用IO流的InputStream将该文件读取到内存中
//读取HTML模板文件new.template
public String readFile(String path) throws IOException{
InputStream is=null;
String result="";
try {
@SuppressWarnings("unused")
int data=;
byte[] by =new byte[];
is = new FileInputStream(path);
while((data=is.read(by))!=-){
//result+=(char)data;
//result=new String(data);
result=new String(by,,by.length);
}
} catch (FileNotFoundException e) {
System.out.println("未找到new.template文件!");
e.printStackTrace();
}
finally{
System.out.println("创建成功!");
is.close();
}
//return result.toString();
return result;
}
String readFile(String path) throws IOException
编写方法toHTml() 替换模板文件,为每条新闻创建一个HTML文件来显示其信息
//读取数据库表,获取新闻列表信息(在此不做讲解)
List<News> list = dao.allInfo();
//编写方法 将从数据库中读取到的数据替换掉news.template文件中的占位符"{}"
String template= fileio.readFile("D:\\news.template"); //替换模板文件,为每条新闻创建一个HTML文件来显示其信息
for (int i = 0; i < list.size(); i++) {
//获取一条新闻信息
News news=list.get(i);
//使用该条新闻信息替换对应占位符
String replacetr = new String();
replacetr=template;
//replace(char oldChar, char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的
replacetr=replacetr.replace("{title}",news.getTitle());
replacetr=replacetr.replace("{author}",news.getAuthor());
replacetr=replacetr.replace("{createTime}",news.getDatetime().toString());
replacetr=replacetr.replace("{content}",news.getContent());
//为该条新闻生成HTML文件
String filepath="D:\\dbtohtml\\new"+i+".html"; fileio.writeFile(filepath,replacetr);
toHtml() throws SQLException, IOException
最终结果如下








