web-dev-qa-db-ja.com

androidで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);
            }
33
locoboy

次のようなものを試してください:

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

お役に立てれば。

49
Harry Joy

最初の部分:

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()
    )
  );

2番目の部分については、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...");
    }
17
Waza_Be

より良い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

0
Joshy Francis