在android中获取并解析CSV文件

时间:2011-03-19 06:47:27

标签: android parsing csv

我正在尝试从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);
            }

3 个答案:

答案 0 :(得分:49)

尝试这样的事情:

    //--- 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
        }
    }

希望这有帮助。

答案 1 :(得分: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()
    )
  );

对于第二部分,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...");
    }

答案 2 :(得分:0)

更好的CSV解析器可以处理带引号的字段

    import android.content.Context;
    import android.widget.Toast;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;

    public class CSVReader {
        private class StringDArray {
            private String[] data=new String[0];
            private int used=0;
            public void add(String str) {
                if (used >= data.length){
                    int new_size= used+1;
                    String[] new_data=new String[new_size];
                    java.lang.System.arraycopy( data,0,new_data,0,used);
                    data=new_data;
                }
                data[used++] = str;
            }
            public int length(){
                return  used;
            }
            public String[] get_araay(){
                return data;
            }
        }
        private  Context context;
        public CSVReader(Context context){
            this.context=context;
        }
        public List read(InputStream inputStream){
            List resultList = new ArrayList();
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String csvLine;
                final char Separator = ',';
                final char Delimiter = '"';
                final char LF = '\n';
                final char CR = '\r';
                boolean quote_open = false;
                while ((csvLine = reader.readLine()) != null) {
                    //String[] row = csvLine.split(",");// simple way
                    StringDArray a=new StringDArray();
                    String token="";
                        csvLine+=Separator;
                    for(char c:csvLine.toCharArray()){
                        switch (c){
                            case LF: case CR:// not required as we are already read line
                                quote_open=false;
                                a.add(token);
                                token="";
                            break;
                            case Delimiter:
                                quote_open=!quote_open;
                            break;
                            case Separator:
                                if(quote_open==false){
                                    a.add(token);
                                    token="";
                                }else{
                                    token+=c;
                                }
                            break;
                            default:
                                token+=c;
                            break;
                        }
                    }
                    if(a.length()>0 ) {
                        if(resultList.size()>0){
                            String[] header_row =(String[]) resultList.get(0);
                            if(a.length()>=header_row.length) {
                                String[] row = a.get_araay();
                                resultList.add(row);
                            }
                        }else{
                            String[] row = a.get_araay();
                            resultList.add(row);//header row
                        }
                    }
                }
                inputStream.close();
            }catch (Exception e){
                Toast.makeText(context,"Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
            return resultList;
        }
    }

用法

    File file=new File(path);
    CSVReader csvReader=new CSVReader(activity.this);
    List csv=csvReader.read( new FileInputStream(file));
    if(csv.size()>0){
        String[] header_row =(String[]) csv.get(0);
        if(header_row.length>1){
            String col1=header_row[0];
            String col2=header_row[1];
        }
    }

    Toast.makeText(activity.this,csv.size() + " rows", Toast.LENGTH_LONG).show();

使用的示例数据
ID,名称
1,测试项目1
“ 2”,“测试项目2”
“ 3”,“测试,项目3”
4,测试项目4