java 根据网址 获取内容 并输出到控制台

package cn.yzy;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scanner;
		URL url;
		Thread readURL;		//new一个线程
		Look look = new Look();
		
		System.out.println("请输入URL地址,如:http://www.yahoo.com");
		scanner = new Scanner(System.in);
		String source = scanner.nextLine();		//接受一个url
		
		try {
			url = new URL(source);
			look.setUrl(url);
			readURL = new Thread(look);		//开启网页内容获取
			readURL.start();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class Look implements Runnable{
	
	URL url;
	
	public void setUrl(URL url) {
		this.url = url;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
	
		try {
			InputStream in = url.openStream();		//打开url
			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 e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/myinc/article/details/22259749
文章标签: 网页内容提取
个人分类: JAVA
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭