简单的页面静态化

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MakeHtml {

public static void main(String[] args){
MakeHtml maker = new MakeHtml();
maker.writeHtml("F:\\c\\sina.html","http://www.google.cn/search?hl=zh-CN&source=hp&q=a&btnG=Google+%E6%90%9C%E7%B4%A2","gb2312");

}

public String getHtml(String httpUrl,String code){
StringBuffer htmlBuffer = new StringBuffer();
try {
//建立资源
URL url = new URL(httpUrl);
//打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent","Mozilla/4.0");
connection.connect();
//打开的连接读取的输入流
InputStream in = connection.getInputStream();
//从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
BufferedReader buf = new BufferedReader(new InputStreamReader(in,code));
String currentLine = "";
while((currentLine=buf.readLine())!=null){
htmlBuffer.append(currentLine+"\n");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return htmlBuffer.toString();
}



public synchronized void writeHtml(String filePath,String httpUrl,String code){
Writer writer = null;

String tempPathFile = filePath.substring(0,filePath.indexOf("."))+"_temp"+filePath.substring(filePath.indexOf("."));
File writerFile = new File(tempPathFile);

boolean existFlag = writerFile.exists();

//目录不存在则生成目录
if(!writerFile.isDirectory()){
File dir = writerFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}

}
//文件存在,则删除文件重建
if(existFlag){
writerFile.delete();
}

try {
//建立新的文件
writerFile.createNewFile();
//输出
writer = new OutputStreamWriter(new FileOutputStream(tempPathFile), code);
writer.write(getHtml(httpUrl,code));
writer.close();

//检查原来的文件是否存在,存在,则删除,将零时文件重命名为旧的文件名,否则,直接重命名
File oldFile = new File(filePath);
boolean oldFileExist = oldFile.exists();
if(oldFileExist){
oldFile.delete();
}
writerFile.renameTo(oldFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(writer!=null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值