如何在读取csv文件时划出新行?

eoxn13cs  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(484)

我试图读取一个文件,其中每一行都有数据成员,用逗号分隔,用于填充对象的数据成员,我尝试使用regex“|”符号分隔“,”和“\n”以及“\r”来到达新行。然而,在读取第一行之后,第二行的第一个数据成员不会立即被读取,而是提前读取“”字符。我使用了错误的正则表达式符号吗?还是我的方法不对?我读到有很多方法可以解决这个问题,并选择使用scanner,因为这似乎是最简单的,使用缓冲区读取器似乎非常混乱,因为它似乎返回数组,而不是单个字符串和int,这是我试图得到的。
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();
    }
hlswsv35

hlswsv351#

你可以用opencsv来实现这一点,这里有一个如何使用这个库的教程。您可以从maven存储库下载这个库。
下面是你需要做的代码,

Reader reader = Files.newBufferedReader(Paths.get("path/to/csvfile.csv"));
CSVReader csvReader = new CSVReader(reader);
List<String[]> dataList = new ArrayList<>();
dataList = csvReader.readAll();

reader.close();
csvReader.close();

Object to_add;

for (String[] rowData : dataList) {
    String textOne = rowData[0];
    String textTwo = rowData[1];
    String textThree = rowData[2];
    int numberOne = Integer.parseInt(rowData[3]);
    int numberTwo = Integer.parseInt(rowData[4]);
    int numberThree = Integer.parseInt(rowData[5]);

    to_add = new Object(textOne, textTwo, textThree, numberOne, numberTwo, numberThree);

    insert(to_add);
}
cedebl8k

cedebl8k2#

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

相关问题