22

I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.

I need to parse this CSV file and save the data in separate arrays.

I have searched for a solution, but I don't get proper idea on how to do this.

1

1 Answer 1

33

I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3

Just add it to your project.

Example code (assuming there is the file assets/test.csv):

        String next[] = {};
        List<String[]> list = new ArrayList<String[]>();

        try {
            CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
            while(true) {
                next = reader.readNext();
                if(next != null) {
                    list.add(next);
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

You can access the imported data with, for example,

list.get(1)[1]

That would return a string.

Sign up to request clarification or add additional context in comments.

4 Comments

@PratikButani the for(;;) does that, so you can do it again after that loop it you want
CSVReader worked for me, after trying tons of other CSV parsing solutions. I am surprised good CSV parsing remains a difficult to implement solution. In my case I had to deal with multilines, and this is the only file which made it work.
What if I wanted to parse a CSV located on a Url?
@Si8 Retrofit. ResponseBody. CSVReader reader = new CSVReader(response.body().charStream());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.