删除CSV文件中的行

时间:2017-07-28 16:33:05

标签: java csv

根据CSV文件中的重复列删除行 例如,CSV文件包含。

CampaignCode | CellCode     | StartDate   | Phone| Account
C000001413   |  A000363363  |  20170601   | 4167292999  | 999999999
C000001414   |  A000363364  |  20170601   | 4167292999  | 999999999

在这里,我想根据Phone列重复项删除完整的行。 预期产量是:     CampaignCode | CellCode | StartDate |电话|帐户     C000001413 | A000363363 | 20170601 | 4167292999 | 999999999

1 个答案:

答案 0 :(得分:-1)

您的解决方案是逐行读取csv文件,将每行放入列表并在您想要的列处检查重复=>将新行列表写入当前文件。您的示例代码(我使用逗号分隔而不是|)

public class CSVReader {
    public static void main(String[] args) throws IOException {

        String csvFile = "csv.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        List<String> lines = new ArrayList<String>();
        boolean isDuplicate = false;

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            isDuplicate = false;
            String[] object = line.split(cvsSplitBy);
            for (String l : lines) {
                if (l.contains(object[3])) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                lines.add(line);
            }
        }
        for (String newL : lines) {
            System.out.println(newL);
        }
        br.close();
    }
}