import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class ReadUrl{
public static void main(String[] args){
Timer timer = new Timer();
//延迟5妙后执行任务,以后每隔10妙执行一次任务
timer.schedule(new SendUrlRequest(),5000,10000);
}
}
class SendUrlRequest extends TimerTask{
@override
public void run(){
String url = "http://www.google.co.uk/";
//获取url对应的网页内容
String content = getContent(url);
//将获取的网页内容写入到硬盘中的一个文件中
writeContent(content);
}
/*
* 获取对应url的网页内容,返回字符串,错误则返回"error open url"
*/
public static String getContent(String srcUrl){
try{
URL url = new URL(srcUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String str = "";
StringBuffer sb = new StringBuffer();
while((str=br.readLine()) != null){
sb.append(str + "/r/n");
}
br.close();
return sb.toString();
}catch(Exception e){
return "error open url":"+srcUrll;
}
}
/*
* 将获取的网页内容写入到硬盘中的一个文件中,写入失败则返回"error write url content"
*/
public static boolean writeContent(String content){
File file = new File("E://index.html");
try{
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = content.getBytes();//把获取的网页内容转换为字节数组
fos.write(bytes,0,bytes.length);//把字节数组里面的内容写入输出流中,即写入到文件中
fos.close();
}catch(Exception e){
return false;
}
return true;
}
}