Java:用URL下载网站实例

package C;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {


	public static void main(String args[]){
		try{
			//创建URL对象,获取地址
			URL url=new URL("https://mini.eastday.com");
			//建立连接
			URLConnection urlconn=url.openConnection();
			System.out.println("成功连接到网站,准备下载...");
			//获得输出流
			InputStream instream=urlconn.getInputStream();
			//把字节流转换为缓冲字符流
			InputStreamReader isr=new InputStreamReader(instream);
			//缓冲字符流
			BufferedReader br=new BufferedReader(isr);
			File file=new File("C:\\Users\\lenovo\\Desktop\\toutiao.html");
			if(!file.exists())
				file.createNewFile();
			BufferedWriter bw=new BufferedWriter(new FileWriter(file));
            String str="";
            while((str=br.readLine())!=null){
                   bw.write(str);
			}
			bw.close();
            br.close();
            System.out.println("文件下载成功");

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

你可能感兴趣的:(java)