正在 Java 上解析 CSV 文件以提取字符串
Parsing CSV file on Java to extract String
在 Java 我制作了一个带有搜索栏的简单程序。我还有一个 CSV 文件 'file.csv',其中包含:
"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"
我可以用这条线打开 Java 上的文件。
String file = "C:\file.csv";
为了验证文件是否存在,我使用了这一行。
if(new File(file).exists()) {
JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}
现在我想解析文件以提取 AD1,如果存在则显示 true,如果不存在则显示 false。我为此声明了 Scanner,但我不知道如何为此设置。
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
scanner.useDelimiter(coma_delimiter);
while(scanner.hasNext()) {
String s1= scanner.next();
System.out.print(s1 +" ");
if(s1.equals(search_field.getText())) {
System.out.print("OKOK");
} else {
System.out.println("NOK");
}
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} finally {
scanner.close();
}
这里的search_field是一个JTextField。
您可能想使用 Apache Commons CSV 代替,因为它是为处理 csv 文件而设计的,下面的示例直接来自他们的页面
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name");
String firstName = record.get("First Name");
}
其中 "Last Name" 和 "First Name" 都是列名。
这样你就可以清楚地查看你的字符串在哪一列了。
Maven 依赖如下:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
您没有逐行阅读文件。您实际上应该做的是获取一行,将其拆分,删除双引号并与您的字符串进行比较。或者您可以将输入的字符串用双引号括起来,然后与拆分后的字符串进行比较。为此,请尝试以下代码:
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
String s1 = null;
String id= null;
String[] tempArr = null;
String searchStr = "\""+search_field.getText()+"\"";
System.out.print("searchStr = " + searchStr );
while(scanner.hasNext()) { // While there are more lines in file
s1= scanner.nextLine();
tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
System.out.print("ID = " + id);
if(id != null && id.equals(searchStr)) {
System.out.print("OKOK");
break; // quit the loop searchStr is found
} else {
System.out.println("NOK");
}
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} finally {
scanner.close();
}
您还可以使用流 API 来单独处理每一行。它也可能有比我的回答更优雅的方法。
final String ENCL = "\"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, List<String>> ans = stream.map(s -> {
String[] split = s.split(",");
if(split.length > 2) {
for(int i = 0; i < split.length; ++i) {
if(split[i].length() >= 2) {
if(split[i].startsWith(ENCL)) {
split[i] = split[i].substring(1);
}
if(split[i].endsWith(ENCL)) {
split[i] = split[i].substring(0, split[i].length()-1);
}
}
}
}
return split;
})
.filter(s->s.length > 2)
.collect(Collectors.toMap(s -> s[0], s-> Arrays.asList(s[1], s[2])));
// do what you will with ans
return ans.containsKey("AD1");
}
catch(IOException ex) {
// do what you will
}
在 Java 我制作了一个带有搜索栏的简单程序。我还有一个 CSV 文件 'file.csv',其中包含:
"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"
我可以用这条线打开 Java 上的文件。
String file = "C:\file.csv";
为了验证文件是否存在,我使用了这一行。
if(new File(file).exists()) {
JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}
现在我想解析文件以提取 AD1,如果存在则显示 true,如果不存在则显示 false。我为此声明了 Scanner,但我不知道如何为此设置。
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
scanner.useDelimiter(coma_delimiter);
while(scanner.hasNext()) {
String s1= scanner.next();
System.out.print(s1 +" ");
if(s1.equals(search_field.getText())) {
System.out.print("OKOK");
} else {
System.out.println("NOK");
}
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} finally {
scanner.close();
}
这里的search_field是一个JTextField。
您可能想使用 Apache Commons CSV 代替,因为它是为处理 csv 文件而设计的,下面的示例直接来自他们的页面
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name");
String firstName = record.get("First Name");
}
其中 "Last Name" 和 "First Name" 都是列名。 这样你就可以清楚地查看你的字符串在哪一列了。
Maven 依赖如下:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
您没有逐行阅读文件。您实际上应该做的是获取一行,将其拆分,删除双引号并与您的字符串进行比较。或者您可以将输入的字符串用双引号括起来,然后与拆分后的字符串进行比较。为此,请尝试以下代码:
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
String s1 = null;
String id= null;
String[] tempArr = null;
String searchStr = "\""+search_field.getText()+"\"";
System.out.print("searchStr = " + searchStr );
while(scanner.hasNext()) { // While there are more lines in file
s1= scanner.nextLine();
tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
System.out.print("ID = " + id);
if(id != null && id.equals(searchStr)) {
System.out.print("OKOK");
break; // quit the loop searchStr is found
} else {
System.out.println("NOK");
}
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} finally {
scanner.close();
}
您还可以使用流 API 来单独处理每一行。它也可能有比我的回答更优雅的方法。
final String ENCL = "\"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, List<String>> ans = stream.map(s -> {
String[] split = s.split(",");
if(split.length > 2) {
for(int i = 0; i < split.length; ++i) {
if(split[i].length() >= 2) {
if(split[i].startsWith(ENCL)) {
split[i] = split[i].substring(1);
}
if(split[i].endsWith(ENCL)) {
split[i] = split[i].substring(0, split[i].length()-1);
}
}
}
}
return split;
})
.filter(s->s.length > 2)
.collect(Collectors.toMap(s -> s[0], s-> Arrays.asList(s[1], s[2])));
// do what you will with ans
return ans.containsKey("AD1");
}
catch(IOException ex) {
// do what you will
}