Simple csv reader

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Simple csv reader

Postby opy001 » Thu Nov 18, 2010 1:12 am

I spent alot of time looking for a simple solution and came up with this little bit of code myself. For future people looking for this like I was you can use this:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.             // reads your file
  2.             BufferedReader in = new BufferedReader(your csv flie source here);
  4.         // creates a new string to put your data in
  5.         String reader = "";
  7.         // looks for the next line that has data
  8.         while ((reader = in.readLine()) != null){
  10.             // tells the reader to slipt the data when it comes to commas
  11.             String[] RowData = reader.split(",");
  13.             // create new strings with your split data in them
  14.             date = RowData[0];
  15.             value = RowData[1];
  17.             // this is where I append the data to my database
  18.             ContentValues values = new ContentValues();
  19.             values.put(CsvProvider.DATE, date);
  20.             values.put(CsvProvider.VALUE, value);
  21.             getContentResolver().insert(CsvProvider.CONTENT_URI, values);
  22.         }
  24.         // ends the loop
  25.         in.close();
Parsed in 0.035 seconds, using GeSHi

My CSV file has no titles and only has 2 column but more than two columns should not be a problem. Just remember to specify what is splitting your columns and for each column add another RowData[#](you have to start with 0). You want to make sure whatever you are going to do with each line is done before you call in.close(). I am using a content provider but you can really do whatever you want with the data like append it to a String[] or whatever else.

While I am using an input stream you can point the BufferedReader to wherever you want. As long as the BufferedReader can read it then it will work.
Experienced Developer
Experienced Developer
Posts: 57
Joined: Sun Jul 11, 2010 5:24 am


Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 5 guests