从URL读取CSV文件

时间:2018-12-30 23:41:42

标签: java

我想从url中读取csv文件(股票数据),但是起始日期和结束日期可变(作为输入),有什么办法可以做到?我已经使用静态日期完成了此操作,但是我已经开始了,但无法继续。

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Scanner;


public class StockData {

    public StockData(String symbol, GregorianCalendar start, GregorianCalendar end) {

        String url = "https://quotes.wsj.com/fx/AEDUSD/historical-prices/download?MOD_VIEW=page&num_rows=300&startDate=12/01/2017&endDate=12/26/2018";

        try {
            URL rowdata = new URL(url);
            URLConnection data = rowdata.openConnection();
            Scanner input = new Scanner(data.getInputStream());
            if (input.hasNext())
                input.nextLine();

            while (input.hasNextLine()) {
                String line = input.nextLine();
                System.out.println(line);
            }
        }
        catch (Exception e) {
            System.out.print(e);
        }
    }

    public static void main(String[] args) {
        String symbol = new String();
        GregorianCalendar start = new GregorianCalendar(2018, 12, 12);
        GregorianCalendar end = new GregorianCalendar(2018, 12, 18);
        StockData test = new StockData(symbol, start, end);
    }
}

1 个答案:

答案 0 :(得分:0)

我在这里代表这个主意,因此您可以进行编码,因为这些更改非常少

  

首先使用`Scanner对象,该对象会读取用户的输入

public static void main(String[] args) {
    String symbol = new String(); //no need this
    Scanner sc = new Scanner(System.in):
    //read user input using scanner object
    String start = //user input
    String end = //user input
    StockData test = new StockData(symbol, start, end);
}
  

StockData构造函数(此方法称为构造函数而不是方法)中,只需将endDatestartDate附加到url

public StockData(String symbol, String start, String end) {

    String url = "https://quotes.wsj.com/fx/AEDUSD/historical-prices/download?MOD_VIEW=page&num_rows=300&startDate="+start+"+&endDate="+end;

    try {
        URL rowdata = new URL(url);
        URLConnection data = rowdata.openConnection();
        Scanner input = new Scanner(data.getInputStream());
        if (input.hasNext()) // remove
            input.nextLine();  //remove

        while (input.hasNextLine()) {
            String line = input.nextLine();
            System.out.println(line);
        }
    }
    catch (Exception e) {
        System.out.print(e);
    }
}