如何使用opencsv读取包含'\'的字符串? [英] How to read a string containing a '\' using opencsv?

查看:63
本文介绍了如何使用opencsv读取包含'\'的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用opencsv读取csv文件时,在字符串末尾遇到"\"时,它无法正常工作.它使字符串的一部分成为",而不是我想要的"\".我猜必须使用某种方法来添加另一个"\",以使其转义为"\"字符吗? Without 必须手动编辑csv文件.我搜索了但没有找到任何内容.

When I'm reading a csv-file using opencsv it doesn't work properly when encountering a '\' at the end of a string. It makes the " part of the string, instead of the '\' as I want to. I guess there must be some method to add another '\' to have it escape the '\'-character instead? Without having to manually edit the csv-file. I have searched but not found anything.

为澄清我的问题,它看起来像这样:

To clarify my problem, it looks like this:

csv文件

"A",       "B",        "C",       "D"
"value 1", "value 2",  "value 3", "value 4"
"value 5", "value 6\", "value 7", "value 8"

我的代码看起来像这样(不是真的,但这显示了我的问题):

My code looks like this (not really, but it shows my problem):

String inFile = "in.csv";
CSVReader reader = new CSVReader(new FileReader(inFile));
String[] line;

while ((line = reader.readNext()) != null) {
    for (int i = 0; i < line.length(); i++) {
        System.out.println(i + " " + line[i]);
    }
}

我希望将其解析为每行每个包含4个元素的String [],但最后一行仅解析为两个元素,如下面的输出所示.

I want this to parse into a String[] with 4 elements each, for each row, but the last row parses only into two elements, as shown in the output below.

1 A
2 B
3 C
4 D
1 value 1
2 value 2
3 value 3
4 value 4
1 value 5
2 value 6",value 7,value 8

我试图将读者更改为:

CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));

但没有任何运气.

推荐答案

也许在Reader的构造函数中更改转义符?

Maybe change the escape character in the constructor of the Reader?

CSVReader(new InputStreamReader(new FileInputStream(inFile)), ',', '"', '|') 

假设您的CSV文件中未使用 |

This is assuming | is not used in your CSV file

这篇关于如何使用opencsv读取包含'\'的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆