解析逗号分隔的CSV的最佳方法,包括不是分隔符的逗号? 【JAVA]

时间:2014-06-18 20:47:53

标签: java parsing csv

我正在尝试将一些数据集解析为数据库。我正在使用的CSV文件的数据用逗号分隔。但是,引号中包含一些数据,其中包括作为该字符串一部分的逗号。在给定此障碍的情况下,如何逐步浏览每一行数据并解析每个数据条目?

编辑:CSV解析器不是一个选项,因为该程序将用于非csv文件。我正在努力减少外部库。

我发现了这个问题,因为我的代码只会解析引号:

while(bufferinput.hasNext()){

            nextline = bufferinput.nextLine();
            dataArray = nextline.split(",");

            for(i = 0; i<colNum;i++){
                //Try-Catch to search through dataArray and push it into sqlData arraylist.
                try{
                    if(!dataArray[i].toString().isEmpty()){
                        sqlData.add(dataArray[i].toString());
                    }
                    //else if used to find empty cells between non empty cells (Have to test to see if opposite of if-statement works)
                    else if(dataArray[i].toString().equals("")){
                        sqlData.add(null);
                    }
                }
                //Catch is necessary to find the cells not at the end of the row in a text file.
                catch(ArrayIndexOutOfBoundsException e){
                    sqlData.add(null);
                }

            }
}

此数据的一个例子是“安大略省,加拿大”,xxxxx .....

地址是最大的原因,因为地址包含逗号。

1 个答案:

答案 0 :(得分:0)

所以这是一个非常简单的解决方案。所有我不得不改变的是我的分裂线:

dataArray = nextline.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");