java 使用 apache commons 获取 CSV 文件头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36269387/
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
Get CSV file header using apache commons
提问by user3382344
I have been looking for the past 2 hours for a solution to my problem in vain. I'am trying to read a CSV File using Apache commons,I am able to read the whole file but my problem is how to extract only the header of the CSV in an array?
过去 2 个小时我一直在寻找解决我的问题的方法,但徒劳无功。我正在尝试使用Apache commons读取 CSV 文件,我能够读取整个文件,但我的问题是如何仅提取数组中 CSV 的标题?
采纳答案by Darshan Mehta
By default, first record read by CSVParser
will always be a header record, e.g. in the below example:
默认情况下,读取的第一条记录CSVParser
将始终是标题记录,例如在下面的示例中:
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
FileReader fileReader = new FileReader("file");
CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
List csvRecords = csvFileParser.getRecords();
csvRecords.get(0)
will return the header record.
csvRecords.get(0)
将返回标题记录。
回答by crehop
I looked everywhere and even the solution above didn't work.. for anyone else with this issue, this does.
我到处寻找,甚至上面的解决方案也不起作用..对于有此问题的其他人,确实如此。
Iterable<CSVRecord> records;
Reader in = new FileReader(fileLocation);
records = CSVFormat.EXCEL.withHeader().withSkipHeaderRecord(false).parse(in);
Set<String> headers = records.iterator().next().toMap().keySet();
回答by Justin Geeslin
BufferedReader br = new BufferedReader(new FileReader(filename));
CSVParser parser = CSVParser.parse(br, CSVFormat.EXCEL.withFirstRecordAsHeader());
List<String> headers = parser.getHeaderNames();
This worked for me. The last line is what you need, extracts the headers found by the parser into a List of Strings.
这对我有用。最后一行是您需要的,将解析器找到的标头提取到字符串列表中。