我正在尝试将CSV文件导入到可以在
Java程序中使用的数组中. CSV文件已成功导入自身,输出显示在终端上,但它会引发错误:
Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 1 at CompareCSV.main(CompareCSV.java:19)
在末尾.另外,当我尝试调用数组中的元素时,它也会显示相同的错误.我的代码如下:
import java.io.*;
import java.util.*;
public class CompareCSV {
public static void main(String[] args) {
String fileName = "sampledata1.csv";
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0,tokenNumber = 0;
while((fileName = br.readLine()) != null) {
lineNumber++;
String[] result = fileName.split(",");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
}
}
catch (FileNotFoundException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
}
解决方法
使用正确的CSV解析器比自己破解错误的解决方案要好得多:
http://opencsv.sourceforge.net/
CSV不是人们可能想到的简单格式(是的,一行可以包含一个,不会分隔两个数据).