我一直在寻找过去 2 小时来解决我的问题的方法。我正在尝试使用Apache commons读取 CSV 文件,我能够读取整个文件,但我的问题是如何仅提取数组中 CSV 的标题?
问问题
18722 次
5 回答
9
默认情况下,读取的第一条记录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)
将返回标题记录。
于 2016-03-28T19:25:32.000 回答
8
我到处找,甚至上面的解决方案也不起作用。对于其他有此问题的人,确实如此。
Iterable<CSVRecord> records;
Reader in = new FileReader(fileLocation);
records = CSVFormat.EXCEL.withHeader().withSkipHeaderRecord(false).parse(in);
Set<String> headers = records.iterator().next().toMap().keySet();
请注意,您的使用.next()
已经消耗了 CSV 的一行。
于 2019-03-12T20:45:36.670 回答
6
BufferedReader br = new BufferedReader(new FileReader(filename));
CSVParser parser = CSVParser.parse(br, CSVFormat.EXCEL.withFirstRecordAsHeader());
List<String> headers = parser.getHeaderNames();
这对我有用。最后一行是您需要的,将解析器找到的标头提取到字符串列表中。
于 2019-08-07T03:13:19.953 回答
1
在科特林:
val reader = File(path).bufferedReader()
val records = CSVFormat.DEFAULT.withFirstRecordAsHeader()
.withIgnoreHeaderCase()
.withTrim()
.parse(reader)
println(records.headerNames)
于 2021-05-17T04:14:52.320 回答
0
下面的代码对我有用:
import java.io.FileReader;
import org.apache.commons.csv.*;
public static String[] headersInCSVFile (String csvFilePath) throws IOException {
//reading file
CSVFormat csvFileFormat = CSVFormat.DEFAULT;
FileReader fileReader = new FileReader(csvFilePath);
CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
List csvRecords = csvFileParser.getRecords();
//Obtaining first record and splitting that into an array using delimiters and removing unnecessary text
String[] headers = csvRecords.get(0).toString().split("[,'=\\]\\[]+");
String[] result = new String[headers.length - 6];
for (int i = 6; i < headers.length; i++) {
//.replaceAll("\\s", "") removes spaces
result[i - 6] = headers[i].replaceAll("\\s", "");
}
return result;
}
于 2022-02-20T05:14:31.973 回答