java 使用java从CSV文件中搜索特定列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6016348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search particular column value from CSV file using java
提问by Jai Android
I want to search by column value and retrieve that particular row from a csv file using java. Suppose I provide "ABC123"than the result should come in this format "ABC123, SW, Php".
我想按列值搜索并使用 java 从 csv 文件中检索该特定行。假设我提供"ABC123"比结果应该以这种格式"ABC123, SW, Php" 出现。
Here is the csv file format:
这是 csv 文件格式:
Employee_Id, Designation, Domain
Employee_Id、职称、域
ABC123, SW, Php
ABC123,软件,PHP
XYZ456, SW, Java
XYZ456,软件,Java
So how do I search any clue. Thanks .
那么我如何搜索任何线索。谢谢 。
采纳答案by Qwerky
Read the file line by line with a BufferedReader
wrapped around a FileReader
. Stop when you hit a line that startsWith
the thing you're looking for. Close the reader and return the line.
逐行读取文件中的行与BufferedReader
缠FileReader
。当你找到startsWith
你正在寻找的东西时停下来。关闭阅读器并返回行。
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. You just have to read each line until you find the one you want.
编辑:
这里没有什么花哨的搜索或优化可以做,除非 CSV 文件有某种你没有提到的顺序。您只需要阅读每一行,直到找到您想要的那一行。
回答by Sean Patrick Floyd
Use OpenCSV to read the CSV file, then find and return the values you need.
使用 OpenCSV 读取 CSV 文件,然后查找并返回您需要的值。
回答by veer7
/**
* 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");
回答by user8867676
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();
}
}