【发布时间】:2014-01-15 06:06:44
【问题描述】:
我有一个 csv 文件,其中包含 5 个标头字段,例如 field1、field2、field3、field4、field5。 该文件包含不同用户的此标头的数据。 有些列可能包含空值,因为只有三列是强制性的。
我想通过指定标题来读取列,就像我指定 field1 和 field3 然后只读取这些列的值。
我尝试使用 opencsv 来执行此操作并读取 opencsv 的所有功能。 我也试过 CSVReader。
这是我的代码:
public void startScanFile(){
String mydemofile=pathtofile;
BufferedReader br =null;
try {
System.out.println("\nEnter the column number that contains ip : ");
br = new BufferedReader(new InputStreamReader(System.in));
ipcolumn = Integer.parseInt(br.readLine());
System.out.println("\nEnter the column number that contains username : ");
br = new BufferedReader(new InputStreamReader(System.in));
usercolumn = Integer.parseInt(br.readLine());
System.out.println("\n Enter the column number that contains password");
br = new BufferedReader(new InputStreamReader(System.in));
passcolumn = Integer.parseInt(br.readLine());
}catch(Exception e){
}
try {
CSVReader csvReader = new CSVReader(new FileReader(mydemofile));
String[] row;
while ((row = csvReader.readNext())!=null){
System.out.println("Col1 is is : " + row[1]);
System.out.println("Col3 is : " + row[3]);
System.out.println("Col4 is : " + row[4]);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
如何只读取指定标头的值?
【问题讨论】:
-
到目前为止你得到了什么?或者至少向我们展示文件内容的示例
-
请阅读this article
-
@RafaEl 我使用 opencsv api 及其函数 readAll 来读取 csv 并从结果中提取信息。