data get

3666 단어
package org.tang.stock;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CatchHTML {
	static String dir = "D:\\stock\\";

	static String stocks = "sz300 310";
	static String urlString = "http://hq.sinajs.cn/list=" + stocks;

	static String lastTime[] = null;
	static BufferedWriter files[] = null;

	public static void main(String[] args) {
		try {
			init();
			boolean flag = true;
			while (flag) {
				String data = captureHtml(urlString);
				flag = handleData(data);
				Thread.sleep(1000);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void init() throws IOException {
		String stock[] = stocks.split(",");
		lastTime = new String[stock.length];
		files = new BufferedWriter[stock.length];
		String directroy = dir
				+ new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		new File(directroy).mkdirs();
		for (int i = 0; i < stock.length; i++) {
			lastTime[i] = "09:15:00";
			FileWriter tofile = new FileWriter(directroy + "\\" + stock[i]
					+ ".txt", true);
			files[i] = new BufferedWriter(tofile);
		}
	}

	private static boolean handleData(String data) throws IOException {
		String stockString[] = data.split(";");
		for (int i = 0; i < stockString.length; i++) {
			StringBuilder buffer = new StringBuilder();
			String sData[] = stockString[i].split(",");
			if (sData[31].compareTo("09:15:00") < 1
					|| (sData[31].compareTo("11:30:20") >=0 && sData[31]
							.compareTo("13:30:00") < 1)) {
				return true;
			} else if (sData[31].compareTo("15:01:00") >=0) {
				if(sData[30].compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) < 1)
					return true;
				return false;
			} else if (sData[31].compareTo(lastTime[i]) > 0) {
				lastTime[i] = sData[31];
			} else {
				continue;
			}
			for (int j = 0; j < 20; j++) {
				buffer.append(sData[10 + j] + ",");
			}
			buffer.append(sData[31]);
			// System.out.println(buffer);
			files[i].write(buffer.toString());
			files[i].newLine();
			files[i].flush();
		}
		return true;
	}

	public static String captureHtml(String urlString) throws Exception {
		URL url = new URL(urlString);
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		InputStreamReader input = new InputStreamReader(
				httpConn.getInputStream(), "GBK");
		BufferedReader bufReader = new BufferedReader(input);
		String line = "";
		StringBuilder contentBuf = new StringBuilder();
		while ((line = bufReader.readLine()) != null) {
			contentBuf.append(line);
		}
		return contentBuf.toString();
	}

}

 
http://biz.finance.sina.com.cn/stock/flash_hq/kline_data.php?symbol=600031&end_date=20110801&begin_date=20110804

좋은 웹페이지 즐겨찾기