java - 将 CSV 文件导出到数组中

标签 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"));
    }
}

到目前为止我还很迷茫。

最佳答案

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"));
    }

关于java - 将 CSV 文件导出到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22186309/

相关文章:

java - 字符数组需要按一定的顺序和位置显示

java - Applet 在 JavaFX 应用程序中不可见

java - httpClient.getConnectionManager() 已弃用-应该改用什么?

c++ - 为什么我不能将二维数组作为指针传递给指针,但可以将一维数组作为指针传递

java - 如何创建带有换行符和引号的 CSV 文件?

python - 使用格式化函数没有得到我想要的

Perl split() 函数不处理保存为变量的管道字符

java - 使用 java 将 .pdf doc 或 .png 图像内容插入到 .docx 文件中

php - 如何通过 PHP 中的内部数组的字段之一对多维数组进行排序?

java - 如何在java bean和Jackson Json中创建VarArgs?