首页 > 解决方案 > 读取CSV文件时如何分隔新行?

问题描述

我正在尝试读取一个文件,其中每行都有数据成员,用逗号分隔,用于填充对象的数据成员,我尝试使用正则表达式“|” 用于分隔“,”和“\n”的符号以及“\r”用于进入新行。但是,在读取第一行之后,不会立即读取第二行的第一个数据成员,而是预先读取“”字符。我使用了错误的正则表达式符号吗?还是我没有使用正确的方法?我读到有很多方法可以解决这个问题并选择使用扫描仪,因为它似乎是最简单的,使用缓冲区读取器似乎非常令人困惑,因为它似乎返回数组而不是我想要得到的单个字符串和整数。

CSV 文件看起来像这样

stringA,stringB,stringC,1,2,3
stringD,stringE,stringF,4,5,6
stringG,stringH,stringI,7,8,9

我的代码看起来像这样

//In list class

public void load() throws FileNotFoundException
    {
        Scanner input = new Scanner(new FileReader("a_file.csv"));

        object to_add; //To be added to the list

        input.useDelimiter(",|\\n|\\r");

        while (input.hasNext())
        {
            String n = input.next(); //After the first loop run, this data gets the value ""
            String l = input.next(); //During this second run, this member gets the data that n was supposed to get, "stringD"
            String d = input.next(); //This one gets "stringE"
            int a = input.nextInt(); //And this one tries to get "stringF", which makes it crash
            int c = input.nextInt();

            to_add = new object(n, l, d, a, b, c); //Calling copy constructor to populate data members

            insert(to_add); //Inserting object to the list
        }

        input.close();
    }

标签: javacsvfilejava.util.scannerdelimiter

解决方案


使用 Apache Commons CSV。这是用户指南https://commons.apache.org/proper/commons-csv/user-guide.html


推荐阅读