zoukankan      html  css  js  c++  java
  • java获取网页源代码并写入本地文件中

     1 import java.io.*;
     2 import java.net.*;
     3 
     4 public class URLDemo {
     5     public static void main(String args[]){
     6         //确定爬取的网页地址
     7         String strurl="http://fx7.top";
     8         //建立url爬取核心对象
     9         try {
    10             URL url=new URL(strurl);
    11             //通过url建立与网页的连接
    12             URLConnection conn=url.openConnection();
    13             //通过链接取得网页返回的数据
    14             InputStream is=conn.getInputStream();
    15             
    16             System.out.println(conn.getContentEncoding());
    17             //一般按行读取网页数据,并进行内容分析
    18             //因此用BufferedReader和InputStreamReader把字节流转化为字符流的缓冲流
    19             //进行转换时,需要处理编码格式问题
    20             BufferedReader br=new BufferedReader(new InputStreamReader(is,"UTF-8"));        
    21             //按行读取并打印
    22             File file = new File("E:/FileTest/test.txt");
    23             //创建本地文件操作对象
    24             if(file.exists()) {
    25             //文件不存在
    26             System.out.println("目标文件不存在!");
    27             try {
    28                 //如果目标文件不存在则自动创建
    29                 file.createNewFile();
    30                 System.out.println("已自动创建文件!");
    31             } catch (IOException e) {
    32                 System.out.println("自动创建文件失败!");
    33             }        
    34         }
    35             String line=null;
    36             while((line=br.readLine())!=null){
    37                 System.out.println(line);
    38                 //创建文件输出流将读取到的网页源代码写入文件
    39                 FileOutputStream fileOutputStream = new FileOutputStream(file,true);
    40                 fileOutputStream.write(line.getBytes());
    41                 fileOutputStream.close();
    42             }
    43             
    44             br.close();
    45         } catch (Exception e) {
    46             // TODO Auto-generated catch block
    47             e.printStackTrace();
    48         }
    49         
    50     }
    51 }        

    7月26 日晚 文件操作回顾记录

  • 相关阅读:
    阿里云的使用运维安装
    阿里云的使用运维安装
    promis:异步编程
    promis:异步编程
    微信开发笔记
    细数那些带打赏功能的平台
    细数那些带打赏功能的平台
    Java Web Services (0)
    4、查询(2)
    COGS——C610. 数对的个数
  • 原文地址:https://www.cnblogs.com/fangmr/p/11252973.html
Copyright © 2011-2022 走看看