java通过一个url读取网站的源代码 储存到本地文件中

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

import javax.swing.JTextArea;

public class Test {
 static BufferedReader reader;

 static JTextArea tPage;

 static URL url;
 static String wenben;
 public static void main(String[] args) {
  tPage = new JTextArea();
  String url = "http://www.baidu.com";   //网站路径
  wenben="F:\\baidu.txt";               //存储路径
  readPage(url);
 }

 public static void readPage(String uu) {
  String line;
  try {
   url = new URL(uu);
   reader = new BufferedReader(new InputStreamReader(url.openStream()));
   while ((line = reader.readLine()) != null) {
    tPage.append(line + "\n");
   }
   cunchu();
   System.out.println("存储成功");
  } catch (Exception ie) {
   tPage.setText("发生输入输出异常 ");
  } finally {
   try {
    if (reader != null)
     reader.close();
   } catch (Exception e) {
   }
  }
 }

 public static void cunchu() {

  File f = new File(wenben);
  try {
   f.createNewFile();
   FileWriter out = new FileWriter(f);
   out.write(tPage.getText());
   out.flush(); // 清空管道
   out.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

你可能感兴趣的:(Java,Java)