Java批量生成html静态页面(高手勿喷)

来源:互联网 发布:oracle数据库日志管理 编辑:程序博客网 时间:2024/04/29 20:03
package cn.utils.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.UUID;import org.junit.Test;/** * 批量生成静态页面 * @version 1.0 * @date 2012.11.20 * @author prosmile * */public class GenerateHTMLUtils { /**  * 根据提供的参数替换模版中的内容(可批量生成),生成文章静态页面到指定目录下,并且返回文章ID对应的文件路径  */ public static Map<String,String> generate(String templatePath,String targetPath,List<Map<String,Object>> params){  String pageName=null;  FileInputStream fis=null;  FileOutputStream fos=null;  Map<String,String> returnUrl=new HashMap<String, String>();  try {   //读取指定模版文件中的数据   fis=new FileInputStream(templatePath);   byte[] by=new byte[fis.available()];   fis.read(by);   fis.close();   String template=new String(by);   for(Map<String,Object> map:params){    String page=new String(template);    //####title#### 为标识性字符, 视模版文件中的实际标识字符为准    page=page.replace("####title####", map.get("title").toString());    page=page.replace("####content####", map.get("content").toString());    page=page.replace("####id####", map.get("id").toString());    //由于每篇文章在数据库中的id是唯一的,所以即使是文件名的前面有了重复但再加上文章的id即可保证文件名的唯一性    pageName=targetPath+"/"+randomPageName(false)+map.get("id")+".html";    File newPage=new File(pageName);    File target=new File(targetPath);    if(!target.exists()){     target.mkdir();     if(!newPage.exists()){      newPage.createNewFile();     }    }    fos=new FileOutputStream(newPage);    fos.write(page.getBytes());    returnUrl.put(map.get("id").toString(), pageName);   }     } catch (Exception e) {   e.printStackTrace();  }finally{   try {    if(fos!=null){     fos.close();    }       } catch (IOException e) {    throw new RuntimeException(e.getMessage());   }     }    return returnUrl; } /**  * 根据参数决定生成文件名的方式<br>  *     true使用UUID生成文件名<br>  *     false使用当前时间生成文件名  */ private static String randomPageName(boolean flag){  if(flag){   return UUID.randomUUID().toString().replace("-", "");  }else{   Calendar calendar=Calendar.getInstance();   return calendar.get(Calendar.YEAR)+""+(calendar.get(Calendar.MONTH)+1)+""+calendar.get(Calendar.DAY_OF_MONTH);  } } @Test public void test(){  List<Map<String,Object>> params=new ArrayList<Map<String,Object>>();  for(int i=1;i<10;i++){   Map<String,Object> map=new HashMap<String, Object>();   map.put("id", "100"+i);   map.put("title", "测试新闻标题"+i);   map.put("content", i+"测试新闻内容测试新闻内容测试新闻内容测试新闻内容测试新闻内容");   params.add(map);  }  Map<String,String> urls=GenerateHTMLUtils.generate("d:/temp.html","d:/page",params);  for(Entry<String, String> en:urls.entrySet()){   System.out.println(en.getKey()+"-->"+en.getValue());  } }}


 

原创粉丝点击