简体   繁体   English

使用Java从CSV文件中搜索特定的列值

[英]Search particular column value from CSV file using java

I want to search by column value and retrieve that particular row from a csv file using java. 我想按列值搜索,并使用java从csv文件中检索特定行。 Suppose I provide "ABC123" than the result should come in this format "ABC123, SW, Php" . 假设我提供“ ABC123” ,则结果应采用“ ABC123,SW,Php”格式。

Here is the csv file format: 这是csv文件格式:

Employee_Id, Designation, Domain Employee_Id,名称,域

ABC123, SW, Php ABC123,SW,Php

XYZ456, SW, Java XYZ456,SW,Java

So how do I search any clue. 那么我该如何搜索任何线索。 Thanks . 谢谢 。

Read the file line by line with a BufferedReader wrapped around a FileReader . BufferedReader包裹FileReader逐行读取文件。 Stop when you hit a line that startsWith the thing you're looking for. 停止当你打一条线startsWith你正在寻找的东西。 Close the reader and return the line. 关闭阅读器并返回该行。

Edit: 编辑:
There's no fancy searching or optimising you can do here, unless the CSV file has some sort of order you haven't mentioned. 除非CSV文件具有您未提及的某种顺序,否则您无法在此处进行任何精美的搜索或优化。 You just have to read each line until you find the one you want. 您只需要阅读每一行,直到找到所需的那一行。

/**
 * returns a string which is comma separate column values for matching row otherwise null. 
 * @param searchColumnIndex
 * @param searchString
 * @return
 * @throws IOException 
 * 
 */
public String searchCsvLine(int searchColumnIndex, String searchString) throws IOException {
    String resultRow = null;
    BufferedReader br = new BufferedReader(new FileReader("somefile.csv"));
    String line;
    while ( (line = br.readLine()) != null ) {
        String[] values = line.split(",");
        if(values[searchColumnIndex].equals(searchString)) {
            resultRow = line;
            break;
        }
    }
    br.close();
    return resultRow;
}

In your case the call will be String result = searchCsvLine(0, "ABC123"); 在您的情况下,调用将为String result = searchCsvLine(0, "ABC123");

使用OpenCSV读取CSV文件 ,然后查找并返回所需的值。

public class Example4 {
  public static void main(String[] args) throws Exception {
    String splitBy = ",";
    BufferedReader br = new BufferedReader(new FileReader("C:\\\sample1.csv"));
    String line;
    while((line = br.readLine()) != null) {
      String[] b = line.split(splitBy);
      System.out.println(b[0]);
    }
    br.close();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM