2013-04-03 45 views
2

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

它为什么会返回任何东西,除了null,那是什么?

+0

这是一个空字符串数组吗? – KidTempo 2013-04-03 22:39:50

+0

我期待它是一个。但是,它的价值与问题中的价值相似。 – CodingInCircles 2013-04-03 22:41:57

+0

空字符串数组与空不相同 - 它仍然是有效的对象,并且会给出类似于您所描述的结果的结果,例如,您将.toString()应用于它。 .length()的结果是什么?我猜0 ... – KidTempo 2013-04-03 22:46:55

回答

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! 
+0

当然,你应该使用'readNext()'而不是'readAll()'来读取整个文件(尤其是如果文件非常大)时,应该只读取前三行。 – KidTempo 2013-04-03 23:35:44

+0

我刚才发现我需要检查令牌的长度,而不是它们是否为空。虽然,我这样做的方式只是蛮横的力量,而不是把任何理由放在它背后 – CodingInCircles 2013-04-03 23:48:38

相关问题