⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 urllinkexample.java

📁 实例精华
💻 JAVA
字号:
/**
*功能:通过一个入口,读出该页上的所有超连接
*用法:java URLLinkExample http://www.sina.com.cn
*@author alex wen
*@version v1.0
*/
import java.net.*;
import java.io.*;
import java.util.*;

public class URLLinkExample
{
	public URLLinkExample()
	{
		super();
	}
	/**
	*判断字串中是否含有http(超连接)
	*@param token
	*@return true or false
	*/
	private boolean hasMatch(String token)//token为枚举出的字符标记
	{
		return token.indexOf("http:")!=-1;//查找该字符标记中是否有http:标记
	}
	/**
	*Trim string
	*@param string
	*@return string has been trimed
	*/
	private String trimURL(String url1)//url1为枚举出的字符标记
	{
		String tempStr=null;
		int beginIndex=url1.indexOf("http");//http子串在父串中的起始索引
		int endIndex=url1.length();//得到终止索引
		tempStr=url1.substring(beginIndex,endIndex);//截取包含有http标记的子串
		endIndex=tempStr.indexOf('"');
		if(endIndex==-1)//如果找不到"标志
			endIndex=tempStr.length();
		return tempStr.substring(0,endIndex);
	}
	
	/**
	*遍历输入的页面里的内容,以找出url
	*@param urlString
	*@return urls
	*/
	public Collection searchURL(String urlString)//urlString为控制台传来的url字符串
	{
		
		URL url2=null;
		URLConnection conn=null;
		String nextLine=null;
		StringTokenizer tokenizer=null;
		Collection urlCollection=new ArrayList();
		try
		{
			url2=new URL(urlString);
			conn=url2.openConnection();//通过调用url2对象的openConnection()取得URLConnection对象
			conn.setDoOutput(true);//如果想使用 URL 连接输出,则设置 DoOutput 标志为 true 
			conn.connect();//连接到指定的资源
			BufferedReader Reader1=new BufferedReader(new InputStreamReader(conn.getInputStream()));//通过URLConnection对象的getInputStream()方法得到InputStream流,然后封装
			while((nextLine=Reader1.readLine())!=null)
			{
				tokenizer=new StringTokenizer(nextLine);//tokenizer 使用缺省的分隔符设置,空格、制表符、换行符和回车
				while(tokenizer.hasMoreTokens())
				{
					String urlToken=tokenizer.nextToken();
					if (hasMatch(urlToken))//调用hasMatch方法,并将枚举出的字符串传过去
						urlCollection.add(trimURL(urlToken));//调用trimURL方法将枚举出的字符标记传入并将返回的值加入到集合中去
				}										
			}
		}
		catch(MalformedURLException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		return urlCollection;
	}
	public static void main(String args[])
	{
		if(args.length!=1)
		{
			System.out.println("USage:java URLLinkExample<url>");
			System.exit(-1);
		}
		String url3=args[0];
		System.out.println("Searching web site:"+url3);
		URLLinkExample example=new URLLinkExample();
		Collection urlCollection=example.searchURL(url3);//调用searchURL方法并将控制台输入的url地址作为参数传入
		Iterator iter=urlCollection.iterator();
		while (iter.hasNext())
		{
			System.out.println(iter.next());
		}
	}
}

	
				
		

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -