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);
  3.  
  4.         // creates a new string to put your data in
  5.         String reader = "";
  6.  
  7.         // looks for the next line that has data
  8.         while ((reader = in.readLine()) != null){
  9.  
  10.             // tells the reader to slipt the data when it comes to commas
  11.             String[] RowData = reader.split(",");
  12.  
  13.             // create new strings with your split data in them
  14.             date = RowData[0];
  15.             value = RowData[1];
  16.  
  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.         }
  23.  
  24.         // ends the loop
  25.         in.close();
Parsed in 0.036 seconds, using GeSHi 1.0.8.4

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.
opy001
Experienced Developer
Experienced Developer
 
Posts: 57
Joined: Sun Jul 11, 2010 5:24 am

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: Yahoo [Bot] and 5 guests