java - 即使 CSV 行中没有值,OpenCSV 也会返回一个字符串

标签 java arrays string csv opencsv

我正在编写一个程序来检查前两行(不包括标题)是否包含任何数据。如果没有,则忽略该文件,如果前两行中的任何一行包含数据,则处理该文件。我正在使用 OpenCSV将标题、第一行和第二行检索到 3 个不同的数组中,然后根据我的要求检查它们。我的问题是,即使前两行为空,reader 也会返回类似 [Ljava.lang.String;@13f17c9e 的内容作为第一行和/或第二行(取决于我的测试文件)。

为什么除了 null 之外,它根本不返回任何东西?

最佳答案

我现在不在我的电脑前,所以请原谅任何错误~ OpenCSV API Javadocs 相当简短,但似乎没有太多内容。读取一行应该将内容解析为一个字符串数组。一个空行应该导致一个空字符串数组,如果您尝试打印它,它会给出类似 [Ljava.lang.String;@13f17c9e 的内容...

我假设以下示例文件:

1 |
2 |
3 | "The above lines are empty", 12345, "foo"

如果你执行 myCSVReader.readAll() 会产生以下内容

// List<String[]> result = myCSVReader.readAll();
0 : []
1 : []
2 : ["The above lines are empty","12345","foo"]

要执行您在问题中描述的内容,请测试长度而不是某种空值检查或字符串比较。

List<String> lines = myCSVReader.readAll();

// lets print the output of the first three lines
for (int i=0, i<3, i++) {
  String[] lineTokens = lines.get(i);
  System.out.println("line:" + (i+1) + "\tlength:" + lineTokens.length);
  // print each of the tokens
  for (String token : lineTokens) {
    System.out.println("\ttoken: " + token);
  }
}

// only process the file if lines two or three aren't empty
if (lineTokens.get(1).length > 0 || lineTokens.get(2).length > 0) {
  System.out.println("Process this file!");
  processFile(lineTokens);
}
else {
  System.out.println("Skipping...!");
}

// EXPECTED OUTPUT:
// line:1  length:0
// line:2  length:0
// line:3  length:3
//         token: The above lines are empty
//         token: 12345
//         token: foo
// Process this file!

关于java - 即使 CSV 行中没有值,OpenCSV 也会返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15799354/

相关文章:

java - while 循环中的菜单

java - Bouncy CaSTLe ASN1 从 BERTaggedObject 检索对象

java - 递归阶乘公式

arrays - bash 字符串到带有空格和额外分隔符的数组

c# - 为什么 WPF Presentation 库在 StringBuilder.ToString() 中包装字符串?

java - 在java中获取文件的根路径

arrays - 命令在终端中有效,但在 Bash 脚本中无效

java - toArray 方法在扩展 ArrayList<> 的类中不起作用

java - String.replace() 没有像我预期的那样工作

c - C 中的数组语法和指针