我需要从csv文件中获取值,为此我需要将分隔符设置为";"并且这些值在"中。
如果我这样尝试:
final CSVReader reader = new CSVReader(new FileReader("file"), ';', '"', 1);
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
System.out.println(Arrays.toString(nextLine));
}
}
编译器给了我这个错误The constructor CSVReader(FileReader, char, char) is undefined
如果我使用它时不带";","&’,1.我得到了文件中的所有内容,但它有一个奇怪的输出。
我的文件获得了10000个值,如:
"00026";"01402118";"Zeitsoldat/in"
"00027";"11101118";"Ackerarbeiter/in"
并且输出看起来像:[00026";"01402118";"Zeitsoldat/in]
[00027";"11101118";"Ackerarbeiter/in]
问题可能是您的代码适用于旧版本的opencsv
。我用3.3
测试了您的代码,它运行得很好。然后,我研究了新版本(5.5.2
(中的不同之处。我注意到CSVReader
的创建有很大不同。以下代码适用于新版本:
CSVParser parser = new CSVParserBuilder().withSeparator(';').withQuoteChar('"').build();
CSVReader reader = new CSVReaderBuilder(new FileReader("input_files/input.csv"))
.withSkipLines(1)
.withCSVParser(parser)
.build();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
System.out.println(Arrays.toString(nextLine));
}
}
输出:
[00026, 01402118, Zeitsoldat/in]
[00027, 11101118, Ackerarbeiter/in]
因此,为了解决您的问题,您必须为您的版本找到合适的代码。如果您使用最新版本,您可以简单地复制上面的代码。