Reading CSV file in resources folder android

前端 未结 5 1799
南方客
南方客 2021-01-04 19:39

I am developing an android app in netbeans. I am trying to read CSV file using opencsv. When I put the file in resources folder and try to read it from there, there\'s an er

5条回答
  •  执笔经年
    2021-01-04 19:57

    Some advices;

    • Create an object for holding one row data into the csv. ( Ex: YourSimpleObject . It provides you to manage the data easily.)
    • Read file row by row and assign to object. Add the object to list. (Ex: ArrayList)

    Code:

    private void readAndInsert() throws UnsupportedEncodingException {
    
    
    ArrayList objList= new ArrayList();
    AssetManager assetManager = getAssets();
    InputStream is = null;
    
                try {
                    is = assetManager.open("questions/question_bank.csv");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
                BufferedReader reader = null;
                reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    
                String line = "";
                StringTokenizer st = null;
                try {
    
                    while ((line = reader.readLine()) != null) {
                        st = new StringTokenizer(line, ",");
                        YourSimpleObject obj= new YourSimpleObject ();
                                        //your attributes
                        obj.setX(st.nextToken());
                        obj.setY(st.nextToken());
                        obj.setZ(st.nextToken());
                        obj.setW(st.nextToken());
    
                        objList.add(sQuestion);
    
                    }
                } catch (IOException e) {
    
                    e.printStackTrace();
                }
    
    
    
    }
    

提交回复
热议问题