Tuesday, October 12, 2010

Reading CSV File using StringTokenizer

There are two ways to read a .csv file and store it in the database.


1)Reading the file line by line and split that line using
StringTokenizer and insert into database.

2)using regular expressions in Java .

Example 1:

Step 1:
File CsvFile =new File("File Path");
FileReader inpFile = new FileReader(CsvFile);
BufferedReader inpReader = new BufferedReader(inpFile);
String inpLine; 

Step 2:
//Reading file line by line
while ((inpLine = inpReader.readLine()) != null) 
{
  String[] Feilds = inpLine.split(",\\s*"); //Specify delimiter
  DoInsertIntoDB(Feilds); //Calling method to insert in Database
}

Step 3:
//Inserting In Database
public void DoInsertIntoDB(String[] inpFeilds)
{
  String Query="insert into emp(id,name)values(?,?)";  
  PreparedStatement InsST=connection.prepareStatement(Query);
  for (int i = 0; i < inpFeilds.length; i++) 
  {
     inpFeilds[i] = inpFeilds[i].replace("\"", "");
  }
  InsST.setString(1, inpFeilds[0]);
  InsST.setString(1, inpFeilds[2]);
  InsST.executeUpdate();
}

Explanation:
In this example i have read the csv file line by line and 
     split the line using StringTokenizer
  In StringTokenizer i have specified , as my delimeter.
      so you can specify whatever delimiter you want.
Disadvantages:
1) If the data in the csv file like "author1,author2" 
     then the above example will read the line and split it 
       into two strings and inserts it into two different columns.
         but you need these full string to be in single column.
           so you can achieve this using regular expression.

No comments:

Post a Comment