代码中有详细的注释, 这里就不再详述(有在项目中使用).1. 可自定义生成文件名和路径.
2. 可自动生成文件夹,方便管理(一般是按日期)
import java.io.*;
import java.net.*;
/**
*
* @author yidwo Lai
* @version 1.0
*
*/
public class MyMakeHtml{
/**
*
* @param sourceURL 动态页面运行路径
*
* @param saveFilePath 生成的静态页面保存路径(带文件名)
*
* @param dirPath 生成的静态页面保存路径(不带文件名,供动态生成文件夹,以便管理)
*
* @return boolean
*/
public static boolean MyMakeHtml(String sourceURL, String saveFilePath,String dirPath) {
boolean flag = false;
RandomAccessFile saveFile = null;
//BufferedRandomAccessFile saveFile;
InputStream inStream = null;
try {
// 如果静态页面已经存在,则删除
File myFile=new File(saveFilePath);
if(myFile.exists()){
myFile.delete();
}
myFile=null;
// 如果给出路径的文件夹不存在,则新建.
if(dirPath.trim().length()>0){
File dirFile = new File(dirPath);
if(!dirFile.exists()){
dirFile.mkdirs();
}
dirFile=null;
}
/**
* 先调用 RandomAccessFile的 RandomAccessFile(String name, String mode)
* 构造方法,如果给定的name!=null, 则转而调用
* RandomAccessFile(File file, String mode)的构造方法
*
*/
saveFile = new RandomAccessFile(saveFilePath, "rw");
// 后台运行动态页面
URL url = new java.net.URL(sourceURL);
// 打开对动态页面的访问连接
URLConnection conn = url.openConnection();
// 获得动态页面的源码
inStream = conn.getInputStream();
// 取得源码的大小
int len = 512;//conn.getContentLength();
byte[] buffer = new byte[len];
int lineRead = 0;
// 写入静态页面
while ( (lineRead = inStream.read(buffer, 0, len)) != -1) { //EOF
saveFile.write(buffer, 0, lineRead);
}
flag = true;
System.out.println("sourceURL = " + sourceURL+" contentLength= "+len);
}catch (Exception e) {
e.printStackTrace();
flag = false;
}finally {
try {
if (saveFile != null) {
saveFile.close();
}
}catch (Exception e) {
}
try {
if (inStream != null) {
inStream.close();
}
}catch (Exception e) {
}
}
return flag;
}
正文
Java动态生成静态页
此篇文章发布距今已超过811天,您需要注意文章的内容或图片是否可用!
还没有评论,来说两句吧...