我有下面的代码块,它使用 OpenCSV 读取 CSV 文件并存储第 7 列。我面临的问题是我在 CSV 文件中使用 ;
作为分隔符,但它也使用 ,
作为分隔符。我怎样才能避免这种情况?
将“”放入 CSV 是不可能的,因为我们从客户端获得了一个不可编辑的文件。
CSVReader reader = null;
String[] nextCsvLine = new String[50];
String splitBy = ";";
int count = 0;
try {
StringReader sr = new StringReader(new String(in, offset, len));
reader = new CSVReader(sr);
while ((nextCsvLine = reader.readNext()) != null) {
for (String linewithsemicolon : nextCsvLine) {
log.debug("Line read : "+linewithsemicolon);
String[] b = linewithsemicolon.split(splitBy);
if (count==0){
count++;
continue;
}
else {
detailItems.add(b[7]);
log.debug("7th position: "+b[7]);
count++;
}
}
最佳答案
使用分隔符为 OpenCSV 的重载版本
CSVReader(reader, ';')
更新(感谢@Matt)-更好地使用:
CSVReaderBuilder(reader)
.withCSVParser(new CSVParserBuilder()
.withSeparator(';')
.build()
).build()
我认为计数
有点不对:
try (CSVReader reader = new CSVReader(sr, ';')) {
String[] nextCsvLine;
while ((nextCsvLine = reader.readNext()) != null) {
int count = 0;
for (String field: nextCsvLine) {
log.debug("Line read : "+linewithsemicolon);
if (count == 6) { // 7th column
detailItems.add(field);
log.debug("7th position: " + field);
}
count++;
}
}
而不是你可以做的 for 循环:
if (nextCsvLine.length > 6) {
detailItems.add(nextCsvLine[6]);
}
第七个字段的索引应为 6。
关于java - 读取分号分隔的 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46845781/