gpt4 book ai didi

java - Apache CSV 解析器 : Issue with ignoring empty lines

转载 作者:行者123 更新时间:2023-12-02 10:43:38 24 4
gpt4 key购买 nike

如何忽略空行?我正在使用下面的代码片段,它不会忽略空行。 CSV 解析器中是否有可用的指针配置来解决此问题?

 public CSVParser parseCSV(InputStream inputStream) {
try {
return new CSVParser(new InputStreamReader(inputStream, StandardCharsets.UTF_8), CSVFormat.DEFAULT
.withFirstRecordAsHeader()
.withIgnoreHeaderCase()
.withSkipHeaderRecord()
.withIgnoreEmptyLines()
.withTrim());
} catch (IOException e) {
throw new IPRSException(e);
}
}

示例文件

h1,h2,h3
d1,d2,d3
,,,

预期输出

d1,d2,d3

最佳答案

Apache CSV 解析器不支持开箱即用的空行,因此最终编写了自定义代码。

private boolean isEmpty(CSVRecord csvRecord){
if (null == csvRecord) return true;
for (int i = 0; i < csvRecord.size(); i++) {
if (StringUtils.isNotBlank(csvRecord.get(i))) {
return false;
}
}
return true;
}


public List<Map<String, Object>> getMapFromCSV(InputStream inputStream) {
try {
CSVParser parser = parseCSV(inputStream);
return getMap(parser.getRecords().stream()
.sequential().filter(v -> !isEmpty(v))
.collect(Collectors.toList()), parser.getHeaderMap());
} catch (IOException e) {
throw new Exception(e);
}
}

private List<Map<String, Object>> getMap (List<CSVRecord> records, Map<String, Integer> headers) {
Map<Integer, String> headerMap = formatHeaderMap(headers);
List<Map<String, Object>> data = new ArrayList<>();
for (int i = 1; i < records.size(); i++) {
Map<String, Object> map = new HashMap<>();
try {
CSVRecord record = records.get(i);
for (int j = 0; j < record.size(); j++) {
map.put(headerMap.get(j), record.get(j));
}
data.add(map);
} catch (Exception e) {
throw new Exception(e);
}
}
return data;
}


private Map<Integer, String> formatHeaderMap(Map<String, Integer> map) {
Map<Integer, String> data = new HashMap<>();
map.forEach((k , v) -> data.put(v, inputSanitizerForUtf8(k)));
return data;
}

关于java - Apache CSV 解析器 : Issue with ignoring empty lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52753552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com