Med*_*usa 7 java csv apache-commons-csv
我想跳过第一行并使用第二行作为标题.
我正在使用apache commons csv中的类来处理CSV文件.
CSV文件的标题位于第二行,而不是第一行(包含坐标).
我的代码看起来像这样:
static void processFile(final File file) {
FileReader filereader = new FileReader(file);
final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
CSVParser parser = new CSVParser(filereader, format);
final List<CSVRecord> records = parser.getRecords();
//stuff
}
Run Code Online (Sandbox Code Playgroud)
我天真地想,
CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(;)
Run Code Online (Sandbox Code Playgroud)
会解决问题,因为它与withFirstRowAsHeader不同,我认为它会检测到第一行不包含任何分号而不是记录.它没有.我试图跳过第一行(CSVFormat似乎认为是标题)
CSVFormat format = CSVFormat.DEFAULT.withSkipHeaderRecord().withFirstRecordAsHeader().withDelimiter(;);
Run Code Online (Sandbox Code Playgroud)
但这也行不通.我能做什么?withFirstRowAsHeader和withFirstRecordAsHeader之间的区别是什么?
如果第一行是标题,则跳过第一行的正确方法是使用其他方法 CSVFormat
CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';').withFirstRecordAsHeader();
Run Code Online (Sandbox Code Playgroud)
在将读者传递给CSVParser:之前,您可能需要阅读第一行:
static void processFile(final File file) {
FileReader filereader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(filereader);
bufferedReader.readLine();// try-catch omitted
final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
CSVParser parser = new CSVParser(bufferedReader, format);
final List<CSVRecord> records = parser.getRecords();
//stuff
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在 org.apache.commons:commons-csv 版本 1.9.0 中使用:
val format = CSVFormat.Builder.create(CSVFormat.DEFAULT)
.setHeader()
.setSkipHeaderRecord(true)
.build()
val parser = CSVParser.parse(reader, format)
Run Code Online (Sandbox Code Playgroud)