将CSV文件导出到数组中

时间:2014-03-05 00:48:56

标签: java arrays csv

我有一个包含不同数据列的CSV文件。

示例:

100, 0.1, 0.5
200, 0.1, 0.1
300, 0.2, 0.5

我想将第一列存储到数组中,将第二列存储到自己的数组中,以便我可以将它们用于数学方程式。

import.java.util.Scanner; 
import java.io.File;

public class Example
{
    public static void main(String[] args) throws Exception 
    {
        Scanner s = new Scanner(new File("C://java//data.txt"));
    }
}

到目前为止,我很失落。

1 个答案:

答案 0 :(得分:1)

You can try this:

public class ReadCSV {
    public static List<List<Double>> getDimensionList(String key) throws Exception  
    {        
        List<List<Double>> listOfDimension = new ArrayList<List<Double>>();
        List<Double> dimensionList = null;      
        File file = null;
        BufferedReader br = null;
        try {
            file = new File(key);   
            br = new BufferedReader(new FileReader(file));

            String strLine = "";
            StringTokenizer dimensionVal = null;
            int lineNumber = 0, tokenNumber = 0;
            while( (strLine = br.readLine()) != null)
            {
                    dimensionVal = new StringTokenizer(strLine, ",");
                    dimensionList = new ArrayList<Double>();
                    while(dimensionVal.hasMoreTokens())
                    {
                        tokenNumber++;
                        dimensionList.add(Double.parseDouble(dimensionVal.nextToken()));

                        if(tokenNumber == 3)
                        {
                            Comparator<Double> comparator = Collections.reverseOrder();
                            Collections.sort(dimensionList,comparator);

                        }
                    }
                    listOfDimension.add(dimensionList);
                    tokenNumber = 0;
                lineNumber++;
            }
        }catch (Exception e) {
            throw new Exception();
        }
        finally
        {
            if(br != null)
                br.close();         
        }       
        return listOfDimension;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getDimensionList("dimension_details.csv"));
    }