在android中获取并解析CSV文件

loc*_*boy 33 csv parsing android

我正在尝试从http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2获取一个csv文件然后解析它以便我可以将价格和价格变成一个对象设置两个属性.有没有办法可以用android库做到这一点?

编辑:这是联合的当前状态(不工作):

HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(uri);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = null;
        while ((line = reader.readLine()) != null){
              result += line + "\n";
              String[] RowData = result.split("\n");
              String name = RowData[0];
              String price = RowData[1];
              String change = RowData[2];

              stock.setPrice(Double.parseDouble(price));
              stock.setTicker(name);
              stock.setChange(change);
            }
Run Code Online (Sandbox Code Playgroud)

Har*_*Joy 50

尝试这样的事情:

    //--- Suppose you have input stream `is` of your csv file then:

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
             String[] RowData = line.split(",");
             date = RowData[0];
             value = RowData[1];
            // do something with "data" and "value"
        }
    }
    catch (IOException ex) {
        // handle exception
    }
    finally {
        try {
            is.close();
        }
        catch (IOException e) {
            // handle exception
        }
    }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • -1.这仅适用于普通的CSV文件; 从长远来看,使用适当的CSV库将是更好的选择. (8认同)
  • @Harry Joy你没有考虑引号.csv会失败:'val1,'val2-1,val2-2",val3' (4认同)
  • @ cfarm54:while循环将逐行读取csv文件,直到没有要读取的行.需要更多解释吗? (2认同)

Waz*_*_Be 17

第一部分:

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";

BufferedReader reader = new BufferedReader(
    new InputStreamReader(
      response.getEntity().getContent()
    )
  );
Run Code Online (Sandbox Code Playgroud)

对于第二部分,Harry是对的,只需按照他的代码,或使用一些库:http://commons.apache.org/sandbox/csv/

CSVReader reader = new CSVReader(** Insert your Reader here **);
    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
        // nextLine[] is an array of values from the line
        System.out.println(nextLine[0] + nextLine[1] + "etc...");
    }
Run Code Online (Sandbox Code Playgroud)