iks_in
iks_in

Reputation: 133

Read and parse CSV file in java

I have two csv files.
CSV File1=csvFrom, //It has two columns, column1=Email(only 5 emails), Column2=Password
CSV File2=csvSendTo //It has only one column = Email. (Thousands of emails).

I am trying to read csvFrom file, I want first email id and its password from first file. Then 20 emails from second csvSendTo file. Want to send emails from first email id and password to these 20 emails. I am able to send email manually with one email id. But when I tried to read it from csv file, its giving me a NullPointerException. Below is my code:I am just pasting the part over here which is giving me an error. Can anyone guide me here? This for loop is wrong here but I am bit confused,so not able to replace with accurate loop.

    BufferedReader br1=null;
    BufferedReader br2=null;
    String line1="",line2="";
    String csvSplitBy=",";
    String strMailFrom="",strPassword="";
    int countCSVFrom=0,countCSVSendTo=0;
    System.out.println("strCSVFrom=" + strCSVFrom + ", strcsvSendTo=" + strCSVSendTo);
    try{
      br1=new BufferedReader(new FileReader(strCSVFrom));
      br2=new BufferedReader(new FileReader(strCSVSendTo));
       String[] strarrFromEmail;
      while((line1=br1.readLine())!=null){
          countCSVFrom+=1;
          strarrFromEmail=line1.split(csvSplitBy);
         // for(int i=countCSVFrom-1;i<=countCSVFrom;i++){
         //     strMailFrom=strarrFromEmail[i];
         //     strPassword=strarrFromEmail[i+1]; //While here its ArrayIndexOutOfBounds Exception
         // } 
         //what is the correct thing to write it over here instead of for loop?
      }
      System.out.println("countcsvfrom="+countCSVFrom + ", line1=" + line1.toString()); //Giving me an error of NullPointerException over here. 

      System.out.println("strFrom="+strMailFrom + ", strPassword="+strPassword);
      while((line2=br2.readLine())!=null){
          countCSVSendTo+=1;
      }
      System.out.println("countcsvsendto="+countCSVSendTo);
    }catch(FileNotFoundException fnfe){
      fnfe.printStackTrace();
    }catch(IOException ioe){
      ioe.printStackTrace();
    }

Upvotes: 0

Views: 565

Answers (2)

Kevin Anderson
Kevin Anderson

Reputation: 4592

The second System.out.println, just after the closing brace of the first while loop, gives the NPE. It uses line1, which the terminating condition of said while loop guarantees will be null at that point.

Upvotes: 1

oliverwiegers
oliverwiegers

Reputation: 195

You could write:

//your code here and try catch block below
try {
    List<String[]> csvLines = new ArrayList<String[]>();
    Files.lines(Paths.get(strCSVFrom)).map(e -> e.split(csvSplitBy)).forEach(csvLines.add(e));
} catch (Exception) {
     //exception handling
}

Upvotes: 0

Related Questions