[英]Apache commons csv skip lines
如何使用apache commons csv跳过输入文件中的行。 在我的文件中,前几行是垃圾有用的元信息,如日期等。找不到任何选项。
private void parse() throws Exception {
Iterable<CSVRecord> records = CSVFormat.EXCEL
.withQuote('"').withDelimiter(';').parse(new FileReader("example.csv"));
for (CSVRecord csvRecord : records) {
//do something
}
}
在开始for-loop
之前使用FileReader.readLine()
。
你的例子:
private void parse() throws Exception {
FileReader reader = new FileReader("example.csv");
reader.readLine(); // Read the first/current line.
Iterable <CSVRecord> records = CSVFormat.EXCEL.withQuote('"').withDelimiter(';').parse(reader);
for (CSVRecord csvRecord: records) {
// do something
}
}
没有内置工具可以跳过未知数量的行。
如果只想跳过第一行(标题行),可以在构建解析器时调用withSkipHeaderRecord()
。
更通用的解决方案是在迭代器上调用next()
:
Iterable<CSVRecord> parser = CSVFormat.DEFAULT.parse(new FileReader("example.csv"));
Iterator<CSVRecord> iterator = parser.iterator();
for (int i = 0; i < amountToSkip; i++) {
if (iterator.hasNext()) {
iterator.next();
}
}
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
System.out.println(record);
}
所以CSVParser.iterator()
绝对不应该在iterator.hasNext()
上抛出异常,因为它使得在错误情况下几乎不可能恢复。
但是有意愿就有方法,我提出了一个有点可行的可怕想法™
public void runOnFile(Path file) {
try {
BufferedReader in = fixHeaders(file);
CSVParser parsed = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in);
Map<String, Integer> headerMap = parsed.getHeaderMap();
String line;
while ((line = in.readLine()) != null) {
try {
CSVRecord record = CSVFormat.DEFAULT.withHeader(headerMap.keySet().toArray(new String[headerMap.keySet().size()]))
.parse(new StringReader(line)).getRecords().get(0);
// do something with your record
} catch (Exception e) {
System.out.println("ignoring line:" + line);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
您可以使用此跳过标题行
Reader excelInput = new FileReader("example.csv");
CSVFormat csvFormat = CSVFormat.EXCEL.withSkipHeaderRecord(true).withHeader("Arm1", "Arm2", "Arm3", "Arm4",
"Arm5", "Arm6");
CSVParser csvParser = new CSVParser(excelInput, csvFormat);
关键是将withSkipHeaderRecord()
设置为true
并指定要在withHeader()
跳过的标题。
如果您知道要跳过的行号,则可以执行以下操作:
for(CVSRecord csvRecord: CSVParser){
if(csvRecord.getRecordNumber() == 1){
continue;
}
}
其中第 1 行是您要跳过的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.