java 读取股票

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class Stock {

public static void main(String[] args) throws Exception {
Stock.current(getDestUrls());
}
public static void  task() throws Exception {
java.util.Timer timer = new java.util.Timer(false);
java.util.TimerTask task = new java.util.TimerTask() {

@Override
public void run() {

try {
Stock.current(getDestUrls());
} catch (Exception e) {
e.printStackTrace();
}
}
};
java.util.Date time = new java.util.Date();
long delay = 10000;

// 启动定时任务,立即执行壹次,然后每隔两秒执行壹次
timer.schedule(task, time, delay);
}
public static List<String> getDestUrls() {
List<String> result = new ArrayList<String>();
result.add("http://hq.sinajs.cn/list=sh000001");
result.add("http://hq.sinajs.cn/list=sz300027");
result.add("http://hq.sinajs.cn/list=sh600999");
result.add("http://hq.sinajs.cn/list=sh600109");
return result;
}
public static void  current(List<String> destUrls) throws Exception {
for (int i = 0; i < destUrls.size(); i++) {
String destUrl = destUrls.get(i);//"http://hq.sinajs.cn/list=sz300027";
String fileName = "C:\\stock";
FileOutputStream fos = null;
  BufferedInputStream bis = null;
  HttpURLConnection httpUrl = null;
  URL url = null;
  int size = 0;
  byte[] buf = new byte[1024];
  url = new URL(destUrl);
  httpUrl = (HttpURLConnection) url.openConnection();
  httpUrl.connect();
  bis = new BufferedInputStream(httpUrl.getInputStream());
  fos = new FileOutputStream(fileName);
  while ((size = bis.read(buf)) != -1)
   fos.write(buf, 0, size);
  fos.close();
  bis.close();
  httpUrl.disconnect();
  String result = FileUtils.readFileToString(new File(fileName),"GBK");
  result = result.substring(21, result.length()-1);
  String name = result.split(",")[0];
  String yesterday = result.split(",")[2];
  String now = result.split(",")[3];
  Float percent = (Float.parseFloat(now)-Float.parseFloat(yesterday))/Float.parseFloat(yesterday);
  DecimalFormat df = new DecimalFormat("###,##0.00%");
  System.err.print(name+",");
  System.err.print(now+",");
  System.err.print(df.format(percent));
  System.err.println();
}

}
}

你可能感兴趣的:(java)