在Java中阅读CSV

6mzjoqzu  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(79)

Snap shot of codeProblematic row example我在阅读csv文件时遇到了问题,这要归功于我提供的csv文件中的行。Schr””这个词通过使读者认为值到此为止来影响读者。我该如何解决这个问题?并非所有行都是这样的。它读起来很好,直到它达到这样的行。我也在使用OpenCSV阅读器。parseInteger()函数只是一个我用来帮助我调试和发现问题的函数。

while ((line = reader.readNext()) != null) {
                int id = parseInteger(line.length > 0 ? line[0] : null,0);
                String title = line.length > 1 ? line[1] : null;
                String abstractText = line.length > 2 ? line[2] : null;
                int maths = parseInteger(line.length > 3 ? line[3] : null, 0);
                int physics = parseInteger(line.length > 4 ? line[4] : null, 0);
                int compsc = parseInteger(line.length > 5 ? line[5] : null, 0);
                int stats = parseInteger(line.length > 6 ? line[6] : null, 0);
                int quantbio = parseInteger(line.length > 7 ? line[7] : null, 0);
                int quantfin = parseInteger(line.length > 8 ? line[8] : null, 0);

                articles.add(new Article(title, id, abstractText, maths, physics, compsc, stats, quantbio, quantfin));

我试着使用制作不同的函数来解决它,但到目前为止没有任何工作。

ovfsdjhp

ovfsdjhp1#

问题是反斜杠和双引号。CSV使用逗号作为值分隔符,因此如果您需要在值中使用逗号,则必须将值括在双引号中。Value1,Value2,"Value,3",Value4
如果你需要使用逗号和双引号,你需要转义它(例如):Value1,Value2,"Value,\"3\"",Value4
我认为,CSV是无效的,解析器被反斜杠的双引号弄糊涂了。
你应该首先清理你的CSV,并且只在应该使用转义序列的地方使用它。
在您的情况下,这是无效的:val1,Schr\"",val3
这将工作:val1,"Schr\"",val3

相关问题