2012年11月18日 星期日

Java 讀取網頁內容並用HashSet過濾資料

import java.io.*;
import java.net.*;
import java.util.*;

public class MyLog01 {
    /**
     * 讀取網頁內容
     *
     * @(Yu-Yu Chen)
     * @version(V 0.1 2012/11/18)
     */
    public static void main(String[] args) throws IOException {

        URL url = new URL("http://tobala.net/download/wiki.myruby.net-May-2012");
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                huc.getInputStream(), "UTF-8"));
        Set<String> ip = new HashSet<String>();

        String str = "";
        StringBuffer sb = new StringBuffer();
        while (null != ((str = br.readLine()))) {
            // 相同 IP 字串不會加入 ip 這個 HashSet 集合物件中
            ip.add(str.substring(0, str.indexOf(' ')));
        }
        br.close();
        System.out.println("共 " + ip.size() + " 個 ip 位址");

        // 列印出所有不相同 IP 位址
        Iterator It = ip.iterator();
        while (It.hasNext()) {
            System.out.print(It.next() + " , ");
        }
    }

}

沒有留言:

張貼留言