我想我发现了一个错误。或者可能不是,但 Super CSV 不能很好地处理。
我正在使用 MapReader 解析一个包含 41 列的 CSV 文件。但是,我得到了那个 CSV - 给我 CSV 的 Web 服务弄乱了一行。 “标题”行是包含 41 个单元格的制表符分隔行。
“错误行”是一个制表符分隔的行,有 36 个单元格,内容没有任何意义。
这是我正在使用的代码:
InputStream fis = new FileInputStream(pathToCsv);
InputStreamReader inReader = new InputStreamReader(fis, "ISO-8859-1");
ICsvMapReader mapReader = new CsvMapReader(inReader, new CsvPreference.Builder('"','\t',"\r\n").build());
final String[] headers = mapReader.getHeader(true);
Map<String, String> row;
while( (row = mapReader.read(headers)) != null ) {
// do something
}
在我上面提到的行中执行 mapReader.read(headers) 时出现异常。这是异常(exception)情况:
org.supercsv.exception.SuperCsvException:
the nameMapping array and the sourceList should be the same size (nameMapping length = 41, sourceList size = 36)
context=null
at org.supercsv.util.Util.filterListToMap(Util.java:121)
at org.supercsv.io.CsvMapReader.read(CsvMapReader.java:79)
at test.MyClass.readCSV(MyClass.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
你觉得我应该怎么做?
我不希望整个应用程序崩溃,只是因为一行被搞乱了,我宁愿跳过那一行。
最佳答案
这是个好问题!作为 super CSV 开发人员,我将研究在 website 上创建一些异常处理示例.
您可以保持简单并使用 CsvListReader(它不关心有多少列),然后自己创建 map :
public class HandlingExceptions {
private static final String INPUT =
"name\tage\nTom\t25\nAlice\nJim\t44\nMary\t33\tInvalid";
public static void main(String[] args) throws IOException {
// use CsvListReader (can't be sure there's the correct no. of columns)
ICsvListReader listReader = new CsvListReader(new StringReader(INPUT),
new CsvPreference.Builder('"', '\t', "\r\n").build());
final String[] headers = listReader.getHeader(true);
List<String> row = null;
while ((row = listReader.read()) != null) {
if (listReader.length() != headers.length) {
// skip row with invalid number of columns
System.out.println("skipping invalid row: " + row);
continue;
}
// safe to create map now
Map<String, String> rowMap = new HashMap<String, String>();
Util.filterListToMap(rowMap, headers, row);
// do something with your map
System.out.println(rowMap);
}
listReader.close();
}
}
输出:
{name=Tom, age=25}
skipping invalid row: [Alice]
{name=Jim, age=44}
skipping invalid row: [Mary, 33, Invalid]
如果您担心使用 Super CSV 的 Util
类(它可能会改变 - 它实际上是一个内部实用程序类),您可以按照我的建议组合 2 个阅读器 here .
您可以 try catch SuperCsvException
,但您可能最终抑制的不仅仅是无效数量的列。我建议捕获的唯一 Super CSV 异常(虽然不适用于您的情况,因为您没有使用单元处理器)是 SuperCsvConstraintViolationException
,因为它表明文件格式正确,但数据不满足您预期的限制条件。
关于java - 搞砸了 CSV 导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585914/