java tutorials and useful tips for developer.

Tuesday 19 January 2016

How to read csv file in java simple code.

Here is the simple code example just copy it and extract your csv file enjoy.


import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;


public class ParseCSVFileReadLineByLine
{
public static void main(String[] args) throws IOException
{
        String filename = "records.csv";
        ParseCSVFileReadLineByLine parseCSVFile = new ParseCSVFileReadLineByLine();
       
        System.out.println("Starting to parse CSV file using opencsv");
        parseCSVFile.parseUsingOpenCSV(filename);
}

private void parseUsingOpenCSV(String filename) throws IOException
{
        CSVReader reader;
        Connection conn=null;
        try
        {
        reader = new CSVReader(new FileReader(filename));
        String[] row;
        row= reader.readNext();
        try{
     Class.forName("com.mysql.jdbc.Driver");
     
     
             conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/scopus","root","badmash");
        while ((row = reader.readNext()) != null)
        {
           
           
         
           
             String[] authaff=row[14].split(";");
           
             for(int j=0;j<authaff.length; j++){
             
                  String[] authaff2=authaff[j].split("\\.,");
                //  for(int k=0; k<authaff2.length; k++){
           
                       System.out.println("Author: "+ authaff2[0] + "affiliateion" + authaff2[1]);
                     
            String sql="insert into authors (`aname`,`affiliation`) values ('"+authaff2[0]+"','"+authaff2[1]+"')";
         
                conn.createStatement().executeUpdate(sql);
             
                 
                     
                     
         
                   
                 
               
             }

}
           
           
           
           
           
              /*  for (int i = 0; i < row.length; i++)
                {
                        // display CSV values
                        System.out.println("Cell column index: " + i);
                        System.out.println("Cell Value: " + row[i]);
                        System.out.println("-------------");
                }*/
        }
       
       
        catch(Exception e){
       
        System.out.println(e.getMessage());
        }
        }
        catch (FileNotFoundException e)
        {
                System.err.println(e.getMessage());
        }
        catch (IOException e)
        {
                System.err.println(e.getMessage());
        }
}
}

0 comments:

Post a Comment

Categories

Popular Posts

Live Stats

Powered by Blogger.