Reading CSV file in resources folder android

无人久伴 提交于 2019-12-01 15:51:27

you should put csv file in assets folder ..

InputStreamReader is = new InputStreamReader(getAssets()
                        .open("filename.csv"));

                BufferedReader reader = new BufferedReader(is);
                reader.readLine();
                String line;
                while ((line = reader.readLine()) != null) {

                    }

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<YourSimpleObject >)

Code:

private void readAndInsert() throws UnsupportedEncodingException {


ArrayList<YourSimpleObject > objList= new ArrayList<YourSimpleObject >();
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();
            }



}

As an alternative, take a look at uniVocityParsers. It provides a vast number of ways to parse delimited files. The example bellow loads a Csv File (see in the picture below) from a res/raw folder into a InputStream object, and read it in a colunar manner (a map where key=Column & value=ColumnValues).

calendario_bolsa.csv

//Gets your csv file from res/raw dir and load into a InputStream.
InputStream csvInputStream = getResources().openRawResource(R.raw.calendario_bolsa);

//Instantiate a new ColumnProcessor
ColumnProcessor columnProcessor = new ColumnProcessor();

//Define a class that hold the file configuration
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setProcessor(columnProcessor);

//Creates a new CsvParser, passing the settings into its construtor:
CsvParser csvParser = new CsvParser(parserSettings);

//Calls parse method, instantiating an InputStreamReader, passing to its constructor the InputStream object
csvParser.parse(new InputStreamReader(csvInputStream));

//Gets the csv data as a Map of Column / column values.
Map<String, List<String>> columnarCsv = columnProcessor.getColumnValuesAsMapOfNames();

To add univocityParsers into your Android Project:

compile group: 'com.univocity', name: 'univocity-parsers', version: '2.3.0'

you may use this code

   try {
                InputStream csvStream = assetManager.open(CSV_PATH);
                InputStreamReader csvStreamReader = new        InputStreamReader(csvStream);
                CSVReader csvReader = new CSVReader(csvStreamReader);
                String[] line;

                // throw away the header
                csvReader.readNext();

                while ((line = csvReader.readNext()) != null) {
                  questionList.add(line);
                }
              } catch (IOException e) {
                e.printStackTrace();
              }

you may download csvreader file from http://sourceforge.net/projects/opencsv/files/latest/download

and import in your project

Using opencsv:

InputStream is = context.getAssets().open(path);
InputStreamReader reader = new InputStreamReader(is, Charset.forName("UTF-8"));
List<String[]> csv = new CSVReader(reader).readAll();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!