日期:2014-05-20 浏览次数:20849 次
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class BookmarkChecker { public static void main(final java.lang.String[] args) throws Exception { BlockingQueue<URL> urls = new LinkedBlockingQueue<URL>(); String [] d=readFileByLines("C:/Documents and Settings/Owner/桌面/xx.txt"); for (int i=0;i<d.length-2;i++){ if(d[i]!=null){ urls.put(new URL(d[i])); }else{ break; } } for(int i=0;i<100;i++) new Thread( new CheckURLWorker(Thread.currentThread().getName(),urls)).start(); } public static String[] readFileByLines(String fileName){ File file = new File(fileName); String [] kk=new String[50000]; BufferedReader reader = null; try { // System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; //一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null){ //显示行号 // System.out.println("line " + line + ": " + tempString); kk[line]=tempString; line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null){ try { reader.close(); } catch (IOException e1) { } } } return kk; } private static class CheckURLWorker implements Runnable { private BlockingQueue<URL> queue; private String name; public CheckURLWorker(String name,BlockingQueue<URL> q){ this.name = name; this.queue = q; } public void run() { for (URL url = queue.poll(); url != null; url = queue.poll()) { try{ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(13000); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); connection.disconnect(); System.out.printf("[%s]%s:%d%n",name,url.toString(),code); } catch (SocketTimeoutException e) { System.out.printf("[%s]%s:%d%n",name,url.toString(),-1); } catch (IOException e) { System.err.println(e); } } } } }