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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

氢_氟_酸   2019-11-18 我要评论

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();
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们