用Java读出一个csv-File。用arraylist填充一个arraylist

时间:2012-12-10 16:06:24

标签: java arrays csv arraylist

我尝试读出一个csv文件。在我的代码中,我读出了csv-File中的Lines。因此,我使用一个arraylist将行中的每个项目添加到arraylist。

读出一行之后,我将数组列表放在另一个数组列表中,然后继续读出下一行,依此类推,然后开启。

现在我有几个问题和一个问题。

1)当我向arraylist添加一个项目时,它总是添加到列表的en中(当我没有给出像我的代码中那样添加项目的具体位置时)?这样就可以保存csv文件的顺序。

2)我发现,当我清除arraylist datatemp以准备读取下一行时,也清除了数组列表数据的内容。如何防止我的代码这样做?

3)有没有办法用我的arraylist数据制作一个普通数组?

4)我的读出csv-File的方式是正确的还是有更好的方法?

public class CSVReader {    

public void ReadCSV (String csvfilepath) {

    BufferedReader CSVFile = null;
    String dataRow = null;
    ArrayList<Float> datatemp = new ArrayList<Float>(); 
    ArrayList<ArrayList<Float>> data = new ArrayList<ArrayList<Float>>(); 

    try {
        CSVFile = new BufferedReader(new FileReader(csvfilepath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        dataRow = CSVFile.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }

    while (dataRow != null){
        String[] dataArray = dataRow.split(",");
        for (String item:dataArray) {
            datatemp.add(Float.valueOf(item));
        }
        try {
            dataRow = CSVFile.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        data.add(datatemp);
        datatemp.clear();
    }

    try {
        CSVFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
} 

4 个答案:

答案 0 :(得分:2)

  

1)这样就可以保存csv文件的顺序。

  

2)如何防止我的代码这样做?

每次都需要创建一个新的tempArrayList:

while (dataRow != null){
    datatemp = new ArrayList<Float>();
  

3)有没有办法用我的arraylist数据制作一个普通数组?

您可以创建一个arraylists数组:

ArrayList[] array = data.toArray(new  ArrayList[data.size()]);

你可以递归地创建一个2D数组,但我会坚持更容易处理的列表列表。

  

4)我的读出csv-File的方式是正确的还是有更好的方法?

使用已经过测试的库there are many of them。正确解析CSV文件要比初看起来要困难得多。

答案 1 :(得分:1)

广告1.您是否阅读过ArrayList参考?方法add()“将指定的元素追加到此列表的末尾。”

广告2.看起来你还没有得到参考的工作方式。只需在循环中声明datatemp,不要清除它,它应该可以正常工作。

广告3.请阅读课程参考。有一种数组方法。在我们的示例中使用它:

Float[] array = data.toArray(new Float[data.size()])

广告4.如果这不是学校作业,则使用图书馆。检查此主题:CSV API for Java

PS:请使用Oracle提供的文档,您的所有答案都在这里:http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

答案 2 :(得分:0)

不考虑细节,为什么不http://opencsv.sourceforge.net/?自己用它,好东西,相信我

答案 3 :(得分:0)

您将datatemp添加到数据阵列,但随后清除阵列。它也将清除数据中的数据。你需要像这样复制数组:

data.add(new ArrayList<Float>( datatemp ) );

我建议使用开源csv库而不是自己进行解析。