import java.io.RandomAccessFile; import java.io.IOException; import java.rmi.RemoteException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.StringTokenizer; import google.webapi.*; public class GoogleLinkChecker { private GoogleSearch searcher; public GoogleLinkChecker(String url, String filename) { searcher = new GoogleSearch(); try { // 引数で指定された URL に対するリンクがあるかを調べる GoogleSearchResult result = searcher.search("link:" + url, 0, 10); // 結果の保存 save(filename, result.getEstimatedTotalResultsCount()); } catch (RemoteException ex) { ex.printStackTrace(); } } private void save(String filename, int count) { try { RandomAccessFile file = new RandomAccessFile(filename, "rw"); String lastLine = "0,0,0"; // 最後の行を読み込む while (true) { String str = file.readLine(); if (str == null) { break; } else { lastLine = str; } } // 前回のリンク数を調べる int lattestCount = 0; if (lastLine != null) { StringTokenizer tok = new StringTokenizer(lastLine, ","); String num = tok.nextToken(); num = tok.nextToken().trim(); lattestCount = Integer.parseInt(num); } // 前回からの差を求めて、ファイルの最後にアペンドする DateFormat format = new SimpleDateFormat("yyyy/MM/dd"); file.writeBytes(format.format(new Date()) + ", " + count + ", " + (count - lattestCount) + "\n"); file.close(); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { if (args.length < 2) { System.err.println("Usage:"); System.err.println(" java GoogleLinkChecker [URL] [csv file]"); return; } new GoogleLinkChecker(args[0], args[1]); } }