Java面向对象程序设计第15章5

5. 利用URLConnetction对象编写程序返回某网站的首页,并将首页的内容存放到文件当中。

import java.net.*;
import java.io.*;

public class firstPage {
    public static void main(String[] args) throws IOException {
        URL url=  new URL("https://www.cnblogs.com/He-Fan/");
        URLConnection con = url.openConnection();
        BufferedReader is=  new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        //三层括号由右往左,以指定字符集获得url的字节输入流,转换为字符输入流,按行读取,更高效
        FileOutputStream fos = new FileOutputStream("D:\\firstPage.html");//指定路径,它会自动新建一个文件
        String line;
        while((line = is.readLine()) != null ) {
            line = line + "\n";
            fos.write(line.getBytes("UTF-8"));//同样要指定字符集
            fos.flush();
        }
        System.out.println("Successful!");
        is.close();
        fos.close();
    }
}

posted @ 2019-11-18 08:47  氢_氟_酸  阅读(147)  评论(0编辑  收藏  举报