1

I have a csv file with 5 columns. I want to fetch the row where the value in the 2nd column matches the user input.

I tried reading a line in the csv. Creating an array with the csv delimiter and then checking for the second value in the array.

Is there a better approach for the same.

Anand B
  • 2,997
  • 11
  • 34
  • 55

2 Answers2

0

Refer below code:

String fName = "C:\\Amit\\abc.csv";
    String input="5";
    String thisLine;
    FileInputStream fis = new FileInputStream(fName);
    DataInputStream myInput = new DataInputStream(fis);

    while ((thisLine = myInput.readLine()) != null) {
        String strar[] = thisLine.split(",");
            if(input.equalsIgnoreCase(strar[1])){
                System.out.println("Found row :"+thisLine);
            }
        }
amicngh
  • 7,831
  • 3
  • 35
  • 54
  • I tried the same way. Is there a way to perform the same without hardcoding the column position. – Anand B Jun 18 '12 at 12:41
0

The CSV format is generally handled with fixed column or row positions. If fixed row and column positions cannot be guaranteed, then you can look at handling the headers to determine the position of the row.

As a general rule, it's going to be much simpler to use a purpose built CSV parser, especially if you do not control the data or output format of the CSV file you are using, as the CSV format has a range of potential corner cases (e.g., commas in the data fields) that cannot be properly handled by String#split(). Two frequently mentioned open-source Java libraries for parsing CSV files are SuperCSV and OpenCSV. OpenCSV can handle parsing CSV files with headers into Java bean objects. SuperCSV can handle both that functionality and parsing a CSV file with headers into a map.

Other CSV libraries can be found listed for this question, this question, and this question.

Community
  • 1
  • 1
ig0774
  • 39,669
  • 3
  • 55
  • 57