0

I am trying to access the CSV file's data using the Java and Apache commons CSV library. I am stucked in a problem. The problem is: "To Display the data of particular row if "Name" Header is equal to the "rahul". when I run the code nothing is printed out there."

The data in exportdata.csv file is :

  • Name,Food,Phone
  • rahul,Rice,9876416884
  • ram,Egg,8437123456
  • rohit,Burger,9814125755
  • amit,chicken,8568934464

And my code is :

public class csvexample {

 public void readfile()
 {
    FileResource fr=new FileResource();
    CSVParser parser=fr.getCSVParser();
    for(CSVRecord record : parser)
    {

        String str=record.get("Name");
        System.out.println(str);

        if(str=="rahul")
        {
        System.out.print(record.get("Name") + "    ");
        System.out.print(record.get("Phone") + "    ");
        System.out.println(record.get("Food"));
        }          
    }
}

I think that the error is in the line if(str=="rahul") , I have checked that the program is not treating the str and "rahul" same when str="rahul" in First iteration of for loop.

yatinsingla
  • 434
  • 6
  • 13
Rahul Singh
  • 184
  • 6
  • I think that this could help https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839 – shadowsheep Oct 06 '17 at 19:48

2 Answers2

1

because they are 2 different String objects, even though they have the same characters. Try if ("rahul".equals(str))

DBug
  • 2,502
  • 1
  • 12
  • 25
0

Not sure but you can try this:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

 public void readFile() {

    String csvFile = "exportdata.csv";
    String line = "";
    String cvsSplitBy = ",";

    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] str = line.split(cvsSplitBy);
            String name = str[0];

            if(name.equals("rahul")){
                System.out.print("Name: " + str[0]);
                System.out.print(" Food: " + str[1]);
                System.out.println(" Phone: " + str[2]);
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

Hope this will help you.

Community
  • 1
  • 1
yatinsingla
  • 434
  • 6
  • 13