解析.csv
文件时,我遍历文件的列标题,并查看其中一个是否等于(忽略大小写)比较id
:
String comparand = "id";
for (String header : headerMap.keySet()) {
if (header.equalsIgnoreCase(comparand)) {
recordMap.put("_id", csvRecord.get(header));
} else {
recordMap.put(header, csvRecord.get(header));
}
}
使用
UTF-8
字符集读取文件:Reader reader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
我使用的CSV解析器库为Apache Commons CSV:
CSVParser csvParser = CSVFormat.DEFAULT
.withDelimiter(delimiter)
.withFirstRecordAsHeader()
.withIgnoreEmptyLines()
.parse(reader);
Map<String, Integer> headerMap = csvParser.getHeaderMap();
当两个字符串的值都为
equalsIgnoreCase()
时,上述false
的计算结果为id
。观察调试器会发现
header
值是一个非紧凑字符串(UTF-16),而comparand
值是一个compact string(ASCII):这是默认行为还是错误?我怎样才能使
equalsIgnoreCase
评估为true
呢? 最佳答案
您的header
值以UTF-16 BOM FFFE
开头。将BOM表与header
进行比较之前,先阅读comparand
。