在 android 中获取和解析 CSV 文件

Posted

技术标签:

【中文标题】在 android 中获取和解析 CSV 文件【英文标题】:Get and Parse CSV file in android 【发布时间】:2011-07-18 15:40:11 【问题描述】:

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

【问题讨论】:

【参考方案1】:

试试这样的:

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

希望这会有所帮助。

【讨论】:

@Harry,非常感谢。出于某种原因,我在 BufferedReader 中找不到 split 方法。您正在使用一个特殊的库吗? @cfarm54: 那么你应该尝试使用SrtingTokenizer @cfarm54:while 循环将逐行读取 csv 文件,直到没有行可读取。需要更多解释吗? -1。这仅适用于琐碎的 CSV 文件;从长远来看,使用适当的 CSV 库会是更好的选择。 @Harry Joy 你没有考虑引号。 csv 会失败:'val1,"val2-1,val2-2",val3'【参考方案2】:

第一部分:

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...");
    

【讨论】:

【参考方案3】:

更好的 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();

使用的样本数据 身份证、姓名 1、测试项目1 "2","测试项目 2" "3","测试,第 3 项" 4、测试项目4

【讨论】:

以上是关于在 android 中获取和解析 CSV 文件的主要内容,如果未能解决你的问题,请参考以下文章

为 CSV 文件制作解析器以获取大量数据

解析纯文本并在android中生成csv

如何从 CSV 文件中获取数据,并将数据解析为两个逗号之间的 INT?

Android / Java,如何在某些字段中使用换行和逗号来处理csv文件?

在 python django 中解析 csv 文件

使用 Node/Express 解析 CSV 文件会吐出奇怪的 \x001 代码