【问题标题】:How to delimit new line when reading CSV file?读取CSV文件时如何分隔新行?
【发布时间】:2020-08-23 08:37:21
【问题描述】:

我正在尝试读取一个文件,其中每行都有数据成员,用逗号分隔,用于填充对象的数据成员,我尝试使用正则表达式“|”用于分隔“,”和“\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();
    }

【问题讨论】:

  • 您可以使用OpenCSV。检查这个tutorial
  • 您的输入文件中没有有效的整数可供扫描,input.nextInt() 在当前示例文件中总是会失败
  • 那些应该代表整数,现在编辑
  • nextLine 然后拆分?

标签: java csv file java.util.scanner delimiter


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用OpenCSV 执行此操作,这里是tutorial 如何使用此库。您可以从Maven Repository 下载该库。

    所以下面是你需要做的代码,

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

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 1970-01-01
      • 2017-06-09
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多