程序

涉及到的知识:

静态化:将数据转换为HTML
DAO模式:
接口
实现类
实体类
数据库连接和关闭的工具类
读文件
/**
* 读文件
* @param fileName
* @return 文件内容才字符串形式返回
*/
public static String readFile(String fileName){
FileReader fr = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String tmp = br.readLine();
while(tmp != null){
sb.append(tmp).append("\r\n");
tmp = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(br != null){
br.close();
}
if(fr != null){
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}

return sb.toString();
}
/**
* 读取文件 
* @param fileName
* @param charSet
* @return
*/
public static String readFile(String fileName, String charSet){
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(fileName);
isr = new InputStreamReader(fis,charSet);
br = new BufferedReader(isr);
String tmp = br.readLine();
while(tmp != null){
sb.append(tmp).append("\r\n");
tmp = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(br != null){
br.close();
}
if(isr != null){
isr.close();
}
if(fis != null){
fis.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}

return sb.toString();
}
数据转换
private NewsDao dao = new NewsDaoImpl();
/**
* 替换模板并生成新的文件
*/
public void replaceContent(){
/*
* 要替换模板,需要完成的步骤
* 1、读取模板内容
* 2、从数据库中读取替换内容
* 3、找到替换字段,然后进行替换
* 4、把替换后的新内容写入新文件中,即生成新文件。
*/
String path = "e:/图片/";
String templateContent = FileUtil.readFile(path + "template.html", "GBK");
System.out.println(templateContent);
List<News> list = dao.getNews();
//把数据库的新闻内容通过循环写入到html文件中
for(News n : list){
String content = templateContent.replace("#{title}", n.getTitle()).
replace("#{author}", n.getAuthor()).
replace("#{date}", n.getPublishDate()).
replace("#{content}", n.getContent());

// System.out.println(content);
FileUtil.writeFile(content, path + n.getTitle() + ".html");
}
}
写文件
/**
* 写文件 
* @param content 需要写入文件的内容
* @param fileName 生成新文件的名称
*/
public static void writeFile(String content, String fileName){
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
bw.write(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bw != null){
bw.close();
}
if(fw != null){
fw.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值