java 如何从opencsv中的特定标题读取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31414120/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:34:53  来源:igfitidea点击:

How to read from particular header in opencsv?

javaopencsv

提问by Yashasvi Raj Pant

I have a csv file. I want to extract particular column from it.For example: Say, I have csv:

我有一个 csv 文件。我想从中提取特定的列。例如:说,我有 csv:

id1,caste1,salary,name1
63,Graham,101153.06,Abraham
103,Joseph,122451.02,Charlie
63,Webster,127965.91,Violet
76,Smith,156150.62,Eric
97,Moreno,55867.74,Mia
65,Reynolds,106918.14,Richard

How can i use opencsv to read only data from header caste1?

如何使用 opencsv 仅读取来自 header caste1 的数据?

采纳答案by Magnilex

There is no built in functionality in opencsv for reading from a column by name.

opencsv 中没有用于按名称读取列的内置功能。

The official FAQ examplehas the following example on how to read from a file:

官方FAQ例如对如何从文件中读取下面的例子:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
   // nextLine[] is an array of values from the line
   System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

You simply fetch the value in second column for each row by accesing the row with nextLine[1](remember, arrays indices are zero based).

您只需通过访问行来获取每一行的第二列中的值nextLine[1](请记住,数组索引是从零开始的)。

So, in your case you could simply read from the second line:

因此,在您的情况下,您可以简单地从第二行读取:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
   System.out.println(nextLine[1]);
}


For a more sophisticated way of determining the column index from its header, refer to the answer from Scott Conway.

有关从其标题确定列索引的更复杂方法,请参阅Scott Conway 的答案

回答by Scott Conway

Magnilex and Sparky are right in that CSVReader does not support reading values by column name. But that being said there are two ways you can do this.

Magilex 和 Sparky 是正确的,因为 CSVReader 不支持按列名读取值。但话虽如此,您有两种方法可以做到这一点。

Given that you have the column names and the default CSVReader reads the header you can search the first the header for the position then use that from there on out;

鉴于您有列名并且默认的 CSVReader 读取标题,您可以首先搜索该位置的标题,然后从那里开始使用它;

private int getHeaderLocation(String[] headers, String columnName) {
   return Arrays.asList(headers).indexOf(columnName);
}

so your method would look like (leaving out a lot of error checks you will need to put in)

所以你的方法看起来像(省略了很多你需要放入的错误检查)

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
int columnPosition;

nextLine = reader.readNext();
columnPosition = getHeaderLocation(nextLine, "castle1");

while ((nextLine = reader.readNext()) != null && columnPosition > -1) {
   // nextLine[] is an array of values from the line
   System.out.println(nextLine[columnPosition]);
}

I would only do the above if you were pressed for time and it was only one column you cared about. That is because openCSV can convert directly to an object that has the variables the same as the header column names using the CsvToBeanclass and the HeaderColumnNameMappingStrategy.

如果您时间紧迫,我只会执行上述操作,而这只是您关心的一栏。这是因为 openCSV 可以使用CsvToBean类和HeaderColumnNameMappingStrategy.

So first you would define a class that has the fields (and really you only need to put in the fields you want - extras are ignored and missing ones are null or default values).

所以首先你会定义一个具有字段的类(实际上你只需要输入你想要的字段 - 忽略额外的字段,缺少的字段是空值或默认值)。

public class CastleDTO {
   private int id1;
   private String castle1;
   private double salary;
   private String name1;

   // have all the getters and setters here....
}

Then your code would look like

然后你的代码看起来像

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
HeaderColumnNameMappingStrategy<CastleDTO> castleStrategy = new HeaderColumnNameMappingStrategy<CastleDTO>();
CsvToBean<CastleDTO> csvToBean = new CsvToBean<CastleDTO>();

List<CastleDTO> castleList = csvToBean.parse(castleStrategy, reader);

for (CastleDTO dto : castleList) {
   System.out.println(dto.getCastle1());
}

回答by ccpizza

From the opencsv docs:

opencsv 文档

Starting with version 4.2, there's another handy way of reading CSV files that doesn't even require creating special classes. If your CSV file has headers, you can just initialize a CSVReaderHeaderAware and start reading the values out as a map:

从 4.2 版开始,还有另一种读取 CSV 文件的简便方法,它甚至不需要创建特殊类。如果您的 CSV 文件有标题,您只需初始化一个 CSVReaderHeaderAware 并开始将值作为地图读取:

  reader = new CSVReaderHeaderAware(new FileReader("yourfile.csv"));
  record = reader.readMap();

.readMap()will return a single record. You need to call .readMap()repeatedly to get all the records until you get nullwhen it runs to the end (or to the first empty line), e.g.:

.readMap()将返回单个记录。您需要.readMap()重复调用以获取所有记录,直到null它运行到最后(或第一个空行)为止,例如:

Map<String, String> values;

while ((values = reader.readMap()) != null) {

    // consume the values here

}

The class also has another constructor which allows more customization, e.g.:

该类还有另一个允许更多自定义的构造函数,例如:

CSVReaderHeaderAware reader = new CSVReaderHeaderAware(
        new InputStreamReader(inputStream),
        0,      // skipLines
        parser, // custom parser
        false,  // keep end of lines
        true,   // verify reader
        0,      // multiline limit
        null    // null for default locale
);

One downside which I have found is that since the reader is lazy it does not offer a record count, therefore, if you need to know the total number (for example to display correct progress information), then you'll need to use another reader just for counting lines.

You also have available the CSVReaderHeaderAwareBuilder

我发现的一个缺点是,由于阅读器很懒,它不提供记录计数,因此,如果您需要知道总数(例如显示正确的进度信息),那么您需要使用另一个阅读器仅用于计数线。

您还可以使用CSVReaderHeaderAwareBuilder

回答by Shawn Mehan

Looking at the javadoc

查看javadoc

if you create a CSVReader object, then you can use the method .readAll to pull the entire file. It returns a List of String[], with each String[] representing a line of the file. So now you have the tokens of each line, and you only want the second element of that, so split them up as they have been nicely given to you with delimiters. And on each line you only want the second element, so:

如果您创建一个 CSVReader 对象,那么您可以使用 .readAll 方法来拉取整个文件。它返回一个 String[] 列表,每个 String[] 代表文件的一行。所以现在你有了每一行的标记,你只想要其中的第二个元素,所以把它们分开,因为它们已经很好地用分隔符提供给你了。在每一行你只想要第二个元素,所以:

public static void main(String[] args){
    String data = "63,Graham,101153.06,Abraham";
    String result[] = data.split(",");
    System.out.print(result[1]);
}