尝试使用Apache Common CSV读取CSV文件时出现重复现象

时间:2018-07-31 21:56:41

标签: java csv apache-commons-csv

我有一个尝试使用Apache Common CSV读取CSV文件的类,到目前为止,我的代码工作正常,除了未获得预期的结果。 我的代码在csv文件中显示第二列的重复项,如下所示:

support@gmail.com
google
google.com
support@gmail.com
google
tutorialspoint
info@tuto.com
google

我的CSV文件

Name,User Name,Password
google.com,support@gmail.com,google
tutorialspoint,info@tuto.com,google

我希望得到这样的东西:

google.com
support@gmail.com
google
tutorialspoint
info@tuto.com
google

这是我的使用Apache CSV解析csv的块

public List<String> readCSV(String[] fields) {
        // HERE WE START PROCESSING THE READ CSV CONTENTS
        List<String> contents = new ArrayList<String>();
        FileReader fileReader = null;
        CSVParser csvFileParser = null;

        // HERE WE START PROCESSING
        if(fields!=null){
            //Create the CSVFormat object with the header mapping
            CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);

            try {

                //Create a new list of student to be filled by CSV file data
                List<String> content=new ArrayList<String>();

                //initialize FileReader object
                fileReader = new FileReader(FilePath);

                //initialize CSVParser object
                csvFileParser = new CSVParser(fileReader, csvFileFormat);

                //Get a list of CSV file records
                List<CSVRecord> csvRecords = csvFileParser.getRecords(); 

                //Read the CSV file records starting from the second record to skip the header
                for (int i = 1; i < csvRecords.size(); i++) {
                    CSVRecord record = csvRecords.get(i);
                    //Create a new student object and fill his data
                    for(int j=0; j<fields.length; j++){
                        content.add(record.get(fields[j]));
                    }
                    // Here we submit to contents
                    contents.addAll(content);
                    System.out.println(contents.size());
                } // end of loop
            } 
            catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fileReader.close();
                    csvFileParser.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
            // Here we return
            return contents;
        }

我不能弄清楚这里缺少什么,欢迎任何帮助。

1 个答案:

答案 0 :(得分:0)

原因是您每次迭代都要添加字符串列表content

                contents.addAll(content);

在每次迭代中清除content或只是更改

                    content.add(record.get(fields[j]));

                    contents.add(record.get(fields[j]));

并删除

                contents.addAll(content);