0

I'm trying to read data from CSV file but data.readNext() looks throwing null and output is not displaying. data.readAll() works but I need to read data cell by cell.

String csvfile = "C:\\Users\\......TestData\\LoginData.csv";
CSVReader data= new CSVReader(new FileReader(csvfile));

String[] cell ;

  while((cell=data.readNext())!=null)
  {
       for(String rec:cell)
       {
           System.out.println(rec);
       }
  }
1

Your code would be throwing a Null when trying to access the element after the last valid element(in the while loop condition), which would be definitely null.

What you can do in this case is wrap the while block in a try-catch block or get the number of valid cells and then use a loop [better option is to use a try-catch block].

String csvfile = "C:\\Users\\......TestData\\LoginData.csv";
CSVReader data= new CSVReader(new FileReader(csvfile));
String[] cell ;

try{
  while((cell=data.readNext())!=null){
       for(String rec:cell){
           System.out.println(rec);
       }
  }
}catch(NullPointerException z){
    System.out.print("Your custom error message");
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.