java 读取URL中的资源

Example13_1.java

import java.net.*;
import java.io.*;
import java.util.*;
public class Example13_1 {
   public static void main(String args[]) {
       Scanner scanner;
       URL url;
       Thread readURL;
       Look look = new Look();
       System.out.println("输入URL资源,例如:http://www.yahoo.com");
       scanner = new Scanner(System.in);
       String source = scanner.nextLine();
       try {  url = new URL(source);
              look.setURL(url);
              readURL = new Thread(look);
              readURL.start();
       }
       catch(Exception exp){
          System.out.println(exp);
       } 
   }
}

Look.java

import java.net.*;
import java.io.*;
public class Look implements Runnable {
   URL url;
   public void setURL(URL url) {
      this.url=url;
   }
   public void run() {
      try { 
        InputStream in = url.openStream();
        byte [] b = new byte[1024];
        int n=-1;
        while((n=in.read(b))!=-1) {
           String str = new String(b,0,n);
           System.out.print(str);
        }
      }
      catch(IOException exp){}
   }
}

 

posted @ 2016-10-23 22:32  我有一壶酒  阅读(1589)  评论(0编辑  收藏  举报