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

本文介绍了一种使用Java IO流读取HTML模板并将其与数据库中的新闻数据相结合的方法,实现动态生成HTML页面的过程。通过解析特定的HTML模板文件,利用数据库中的新闻数据替换模板中的占位符,为每条新闻生成单独的HTML文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在我们的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);
复制代码

 

最终结果如下

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值