2

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

为什么它会返回任何东西,除了 a null,也就是说?

4

1 回答 1

1

我现在不在我的电脑前,所以请原谅任何错误~ 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!
于 2013-04-03T23:33:57.647 回答